yup#string TypeScript Examples

The following examples show how to use yup#string. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BankAccountForm.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
validationSchema = object({
  bankName: string().min(5, "Must contain at least 5 characters").required("Enter a bank name"),
  routingNumber: string()
    .length(9, "Must contain a valid routing number")
    .required("Enter a valid bank routing number"),
  accountNumber: string()
    .min(9, "Must contain at least 9 digits")
    .max(12, "Must contain no more than 12 digits")
    .required("Enter a valid bank account number"),
})
Example #2
Source File: Application.validate.schema.ts    From msclub-backend with GNU General Public License v3.0 6 votes vote down vote up
applicationSchema = object({
	studentId: string().length(10).required("SLIIT ID is required"),
	name: string().required("Name is required"),
	email: string().required("Email is required").email("Email is not valid"),
	contactNumber: string()
		.required("Phone number is required")
		.min(10)
		.max(10)
		.matches(contactNumberRegEx, "Invalid phone number"),
	currentAcademicYear: string().required("Academic year is required"),
	selfIntroduction: string().required("Self introduction is required"),
	reasonForJoin: string().required("Reason for join is required"),
	linkedIn: string().required("LinkedIn profile is required").matches(webURLRegEx, "Invalid link"),
	gitHub: string().required("GitHub profile is required").matches(webURLRegEx, "Invalid link"),
	blog: string().matches(webURLRegEx, "Invalid link"),
	experiences: string().max(1500, "Character count exceed: (Maximum: 1500)"),
	challenges: string().max(1500, "Character count exceed: (Maximum: 1500)"),
	goal: string().required("Goal is required"),
	skillsAndTalents: array().of(string()),
	pastWork: string().max(1500, "Character count exceed: (Maximum: 1500)"),
})
Example #3
Source File: validation.ts    From frontend with MIT License 6 votes vote down vote up
setLocale({
  mixed: {
    default: 'validation:invalid',
    required: 'validation:required',
  },
  string: {
    min: ({ min }: { min: number }) => ({
      key: 'validation:field-too-short',
      values: { min },
    }),
    max: ({ max }: { max: number }) => ({
      key: 'validation:field-too-long',
      values: { max },
    }),
    email: 'validation:email',
  },
})
Example #4
Source File: Schema.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
Schema = object().shape({
  metaValues: object().shape({
    init_input: string(),
    init_output: string(),
    async_init_input: string(),
    async_init_output: string(),
    handle_input: string(),
    handle_output: string(),
    async_handle_input: string(),
    async_handle_output: string(),
    meta_state_input: string(),
    meta_state_output: string(),
    types: string(),
  }),
  programValues: object().shape({
    value: number().required('This field is required').min(0, 'Initial value should be more or equal than 0'),
    payload: payloadSchema,
    gasLimit: number().min(0, 'Initial value should be more than 0'),
    programName: string().max(50, 'Name value should be less than 50'),
  }),
})
Example #5
Source File: foodForm.ts    From calories-in with MIT License 6 votes vote down vote up
foodFormSchema = object().shape({
  name: string()
    .required('Please add a name')
    .test(
      'uniqueName',
      'This name has already been used',
      (currentName, { options }) => {
        if (currentName === undefined) {
          return true
        }

        const { allFoods, food } = options.context as FoodFormSchemaContext

        const sameFoodExists = allFoods.some(({ name, id }) => {
          const haveSameNames = currentName.toLowerCase() === name.toLowerCase()
          return food ? id !== food.id && haveSameNames : haveSameNames
        })

        return !sameFoodExists
      }
    ),
  categoryId: number()
    .notOneOf([0], 'Please select category')
    .typeError('Please select category'),
  energy: string().required('Please enter energy'),
  servingSizeInGrams: string().required('Please enter a value'),
})
Example #6
Source File: variantNameForm.ts    From calories-in with MIT License 6 votes vote down vote up
variantNameFormSchema = object().shape({
  name: string()
    .required('Please add a name')
    .test(
      'uniqueName',
      'This name has already been used',
      (currentName, { options }) => {
        if (currentName === undefined) {
          return true
        }

        const {
          variantsForms,
          variantForm,
        } = options.context as VariantNameFormSchemaContext

        const sameVariantFormExists = variantsForms.some(
          ({ name, fieldId }) => {
            const haveSameNames =
              currentName.toLowerCase() === name.toLowerCase()
            return variantForm
              ? fieldId !== variantForm.fieldId && haveSameNames
              : haveSameNames
          }
        )

        return !sameVariantFormExists
      }
    ),
})
Example #7
Source File: ShippingForm.tsx    From storefront with MIT License 6 votes vote down vote up
validationSchema: SchemaOf<Omit<CustomerAddressInput, 'email' | 'overwrite' | 'phone'>> =
  object({
    address1: string().label('Street address').max(100).required(),
    address2: string().min(0).max(254),
    city: string().label('City').max(25).required(),
    company: string().label('Company').min(0).max(35),
    country: mixed().label('Country').oneOf(Object.values(CountriesEnum)).required(),
    firstName: string().label('First name').max(35).required(),
    lastName: string().label('Last name').max(35).required(),
    postcode: string().label('Postcode').min(2).max(9).required(),
    state: string().label('State').min(0).max(254),
  })
Example #8
Source File: BillingForm.tsx    From storefront with MIT License 6 votes vote down vote up
validationSchema: SchemaOf<Omit<CustomerAddressInput, 'overwrite'>> = object({
  address1: string().label('Street address').max(100).required(),
  address2: string().min(0).max(254).nullable(),
  city: string().label('City').max(25).required(),
  company: string().label('Company').min(0).max(35).nullable(),
  country: mixed().label('Country').oneOf(Object.values(CountriesEnum)).required(),
  email: string().label('Email').email().min(11).max(254).required(),
  firstName: string().label('First name').max(35).required(),
  lastName: string().label('Last name').max(35).required(),
  phone: string().label('Phone number').min(10).max(15).required(),
  postcode: string().label('Postcode').min(2).max(9).required(),
  state: string().label('State').min(0).max(254).nullable(),
})
Example #9
Source File: commonFormSchemes.ts    From netify with BSD 2-Clause "Simplified" License 6 votes vote down vote up
headersSchema = array().of(
	object({
		name: string().when('value', {
			is(value) {
				return !value;
			},
			then: string(),
			otherwise: string().required('Name is required when the value is not empty'),
		}),
		value: string(),
	}),
)
Example #10
Source File: commonFormSchemes.ts    From netify with BSD 2-Clause "Simplified" License 6 votes vote down vote up
requestBodySchema = object({
	type: mixed<'Original' | RequestBodyType>().oneOf(['Original', ...requestBodyTypesList]),
	textValue: string(),
	formValue: array().of(
		object({
			key: string().when('value', {
				is(value) {
					return !value;
				},
				then: string(),
				otherwise: string().required('Key is required when the value is not empty'),
			}),
			value: string(),
		}),
	),
})
Example #11
Source File: UserSettingsForm.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
validationSchema = object({
  firstName: string().required("Enter a first name"),
  lastName: string().required("Enter a last name"),
  email: string().email("Must contain a valid email address").required("Enter an email address"),
  phoneNumber: string()
    .matches(phoneRegExp, "Phone number is not valid")
    .required("Enter a phone number"),
  defaultPrivacyLevel: mixed<DefaultPrivacyLevel>().oneOf(DefaultPrivacyLevelValues),
})
Example #12
Source File: commonFormSchemes.ts    From netify with BSD 2-Clause "Simplified" License 6 votes vote down vote up
responseBodySchema = object({
	type: mixed<'Original' | ResponseBodyType>().oneOf(['Original', ...responseBodyTypesList]),
	textValue: string().when('type', {
		is: ResponseBodyType.Base64,
		then: string().matches(/^[A-Za-z0-9+/]*(={1,3})?$/, 'Invalid Base 64'),
		otherwise: string(),
	}),
	fileValue: mixed<File>().notRequired(),
})
Example #13
Source File: SignUpForm.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
validationSchema = object({
  firstName: string().required("First Name is required"),
  lastName: string().required("Last Name is required"),
  username: string().required("Username is required"),
  password: string()
    .min(4, "Password must contain at least 4 characters")
    .required("Enter your password"),
  confirmPassword: string()
    .required("Confirm your password")
    .oneOf([ref("password")], "Password does not match"),
})
Example #14
Source File: validation.ts    From frontend with MIT License 5 votes vote down vote up
companyName = string().trim().min(2).max(50)
Example #15
Source File: CommentForm.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 5 votes vote down vote up
validationSchema = object({
  content: string(),
})
Example #16
Source File: validation.ts    From frontend with MIT License 5 votes vote down vote up
name = string().trim().matches(noNumbersRegex, customValidators.name).min(2).max(50)
Example #17
Source File: validation.ts    From remote-office-hours-queue with Apache License 2.0 5 votes vote down vote up
queueNameSchema = string().trim().required(blankText).max(100, createRemainingCharsMessage)
Example #18
Source File: validation.ts    From remote-office-hours-queue with Apache License 2.0 5 votes vote down vote up
queueDescriptSchema = string().trim().max(1000, createRemainingCharsMessage)
Example #19
Source File: validation.ts    From remote-office-hours-queue with Apache License 2.0 5 votes vote down vote up
meetingAgendaSchema = string().trim().max(100, createRemainingCharsMessage)
Example #20
Source File: validation.ts    From remote-office-hours-queue with Apache License 2.0 5 votes vote down vote up
queueLocationSchema = string().trim().max(100, createRemainingCharsMessage)
Example #21
Source File: validation.ts    From remote-office-hours-queue with Apache License 2.0 5 votes vote down vote up
uniqnameSchema = string().trim().lowercase()
    .min(3, 'Uniqnames must be at least 3 characters long.')
    .max(8, 'Uniqnames must be at most 8 characters long.')
    .matches(/^[a-z]+$/i, 'Uniqnames cannot contain non-alphabetical characters.')
Example #22
Source File: notesForm.ts    From calories-in with MIT License 5 votes vote down vote up
notesFormSchema = object().shape({
  name: string(),
})
Example #23
Source File: ruleFormSchema.ts    From netify with BSD 2-Clause "Simplified" License 5 votes vote down vote up
ruleFormSchema = object({
	label: string().notRequired(),
	filter: object({
		url: string(),
		resourceTypes: array().of(mixed<ResourceType>().oneOf(resourceTypesList)),
		methods: array().of(mixed<RequestMethod>().oneOf(requestMethodsList)),
	}),
	actionType: mixed<RuleActionsType>().oneOf(ruleActionsTypesList),
	actionConfigs: object({
		[RuleActionsType.Breakpoint]: object({
			stage: mixed<BreakpointStage>()
				.oneOf(breakpointStagesList)
				.default(BreakpointStage.Both),
		}),
		[RuleActionsType.Mutation]: object({
			request: object({
				endpoint: string().matches(
					/^((https?:)|(\[protocol]))\/\/.+/,
					'The endpoint url should be started with a protocol (or suitable macros) and have a hostname',
				),
				method: mixed<RequestMethod>()
					.oneOf(requestMethodsList)
					.notRequired(),
				setHeaders: headersSchema,
				dropHeaders: array().of(string()),
				body: requestBodySchema,
			}),
			response: object({
				statusCode: statusCodeSchema.notRequired(),
				setHeaders: headersSchema,
				dropHeaders: array().of(string()),
				body: responseBodySchema,
			}),
		}).required(),
		[RuleActionsType.LocalResponse]: object({
			statusCode: statusCodeSchema.required('Status code is required'),
			headers: headersSchema,
			body: responseBodySchema,
		}),
		[RuleActionsType.Failure]: object({
			reason: mixed<ResponseErrorReason>().oneOf(responseErrorReasonsList),
		}),
	}).required(),
}).required()
Example #24
Source File: validation.ts    From frontend with MIT License 5 votes vote down vote up
phone = string().trim().matches(phoneRegex, customValidators.phone).min(9).max(15)
Example #25
Source File: validation.ts    From frontend with MIT License 5 votes vote down vote up
email = string().trim().email()
Example #26
Source File: GuestView.tsx    From tailchat with GNU General Public License v3.0 5 votes vote down vote up
GuestView: React.FC = React.memo(() => {
  const history = useHistory();
  const navToView = useNavToView();
  const navRedirect = useSearchParam('redirect');
  const [nickname, setNickname] = useState('');

  const [{ loading }, handleCreateTemporaryUser] = useAsyncRequest(async () => {
    await string().required(t('昵称不能为空')).max(16).validate(nickname);

    const data = await createTemporaryUser(nickname);

    setGlobalUserLoginInfo(data);
    await setUserJWT(data.token);

    if (isValidStr(navRedirect)) {
      history.push(decodeURIComponent(navRedirect));
    } else {
      history.push('/main');
    }
  }, [nickname, history, navRedirect]);

  return (
    <div className="w-96 text-white">
      <div className="mb-4 text-2xl">{t('创建访客')}</div>

      <div>
        <div className="mb-4">
          <div className="mb-2">{t('昵称')}</div>
          <input
            className="appearance-none rounded-md relative block w-full px-4 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 text-base sm:text-sm"
            placeholder={t('想要让大家如何称呼你')}
            type="text"
            value={nickname}
            onChange={(e) => setNickname(e.target.value)}
          />
        </div>

        <button
          className="w-full py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
          disabled={loading}
          onClick={handleCreateTemporaryUser}
        >
          {loading && <Spinner />}
          {t('立即进入')}
        </button>

        <button
          className="w-full py-2 px-4 border border-transparent text-sm text-left font-medium text-white disabled:opacity-50"
          disabled={loading}
          onClick={() => navToView('/entry/login')}
        >
          <Icon icon="mdi:arrow-left" className="mr-1 inline" />
          {t('返回登录')}
        </button>
      </div>
    </div>
  );
})
Example #27
Source File: schema.ts    From tailchat with GNU General Public License v3.0 5 votes vote down vote up
fieldSchema = {
  string,
  ref,
}
Example #28
Source File: index.ts    From qrcode-pix with MIT License 5 votes vote down vote up
function QrCodePix({
    version,
    key,
    city,
    name,
    value,
    message,
    cep,
    transactionId = '***',
    currency = 986,
    countryCode = 'BR',
}: QrCodePixParams) {
    string().equals(['01'], 'Version not supported').validateSync(version);

    string()
        .min(2, 'countryCode: 2 characters')
        .max(2, 'countryCode: 2 characters')
        .nullable()
        .validateSync(countryCode);

    string().min(8, 'cep: 8 characters').max(8, 'cep: 8 characters').nullable().validateSync(cep);

    if (String(value) === '0') {
        value = undefined;
    }

    number().nullable().positive('Value must be a positive number').validateSync(value);

    string().max(25, 'transactionId: max 25 characters').nullable().validateSync(transactionId);

    const payloadKeyString = generateKey(key, message);

    const payload: string[] = [
        genEMV('00', version),
        genEMV('26', payloadKeyString),
        genEMV('52', '0000'),
        genEMV('53', String(currency)),
    ];

    if (value) {
        payload.push(genEMV('54', value.toFixed(2)));
    }

    name = String(name)
        .substring(0, 25)
        .toUpperCase()
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '');

    city = String(city)
        .substring(0, 15)
        .toUpperCase()
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '');

    payload.push(genEMV('58', countryCode.toUpperCase()));
    payload.push(genEMV('59', name));
    payload.push(genEMV('60', city));

    if (cep) {
        payload.push(genEMV('61', cep));
    }

    payload.push(genEMV('62', genEMV('05', transactionId)));

    payload.push('6304');

    const stringPayload = payload.join('');
    const buffer = Buffer.from(stringPayload, 'utf8');

    const crc16CCiTT = crc(16, 0x1021, 0xffff, 0x0000, false);
    const crcResult = crc16CCiTT(buffer).toString(16).toUpperCase().padStart(4, '0');

    const payloadPIX = `${stringPayload}${crcResult}`;

    return {
        payload: () => payloadPIX,
        base64: (options?: QRCodeToDataURLOptions) => qrcode.toDataURL(payloadPIX, options),
    };
}
Example #29
Source File: Schema.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
payloadSchema = lazy((value) => {
  if (typeof value === 'object') {
    return object();
  }

  return string().required('This field is required');
})