Search code examples
reactjsvalidationyup

How to validate each character in firstName with yup?


I have hard times validating every single character in input. I want to return invalid input for firstName if there is something beside simple alphabet characters, ie. if there are numbers or special characters.

This is my code, and i am looking for something which could afford me desired behavior:

const FormSchema = yup.object().shape({
    firstName: yup
      .string()
      .max(40).
      .required(),

...

<Formik initialValues={initialValues} validationSchema={FormSchema} validateOnMount onSubmit={formSubmit}>
  <Field name="firstName">
    {(props: FieldProps) => (
      <TextField {...props.field} {...textErrors(props.meta)} fullWidth label={t('firstName')} type="text" />
                )}
  </Field>

Solution

  • Well, it turned out that when i was trying yesterday i was missing dollar sign $, for telling regex to search to the end of the given string input.

    const FormSchema = yup.object().shape({
        firstName: yup
          .string()
          .matches(/^[A-Za-z ]*$/, 'Please enter valid name')
          .max(40)
          .required(),