22

I have been working on a react form and I need to restrict users to put special characters and allow only these ones: [A-Za-z].

I have tried the below code but I am still able to insert inside special characters such as: '♥', '>', '+', etc.

export default Component (props {
  ...
  return (
   <input 
    pattern={props.pattern}
   /> 
  )
}

And I am sending it as a prop to my form:

<Component 
pattern="[A-Za-z]+"
/>

Can you let me know what I am missing and point out what could be the issue? Many thanks.

  • 1
    You need an onChange event to validate the pattern using pattern.test function. – Eric Jul 20 '20 at 17:30
  • You may check out full-blown demos of form validation for [MaterialUI-styled](https://stackoverflow.com/a/62962725/11299053) form and the one [based on SemanticUI](https://stackoverflow.com/a/62885267/11299053). Hopefully, either of those will give you a clue about how to approach your problem. – Yevhen Horbunkov Jul 20 '20 at 17:37
  • 1
    You may try `pattern="^[a-zA-Z]+$"` – Yevhen Horbunkov Jul 20 '20 at 17:38

4 Answers4

42

The pattern attribute on input only works on submit in vanilla HTML forms.

If you're using react-hook-form, it should be in the ref, like this:

<input
    name="email"
    ref={register({
      required: "Required",
      pattern: {
        value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
        message: "invalid email address"
      }
    })}
  />

please have a check on react-hook-form doc. Additionally for simple form use case you can try cksform library.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
anunaki
  • 989
  • 9
  • 16
  • This only works on submit, but I need to restrict user to input special characters before. –  Jul 20 '20 at 18:35
  • 1
    I don't know how to use it best with react-hook-form, but converting the field to controlled component and use html5 validation api may work. Please check https://codesandbox.io/s/react-hook-form-v6-seterror-swr80 . The firstName field is restricted with the pattern.I will add this use case in cksform library. – anunaki Jul 20 '20 at 19:11
17

If you are using react-hook-form v7 then use this:

<input
    placeholder="Email"
    {...register('email', {
        required: 'Email is required',
        pattern: {
            value: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: 'Please enter a valid email',
        },
    })}
    type="email"
    required
    className="input"
/>
{formState.errors.email?.message && (
     <FormError errorMessage={formState.errors.email?.message} />
)}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Adarsha Acharya
  • 309
  • 3
  • 4
1

Assuming your input is name then you can just exclude those special characters, use the every function on pattern, basically check that each pattern is true otherwise throw an error message that you can override as you prefer

 <label htmlFor="name">Name</label>
  <input
    type="text"
    name="name"
    id="name"
    ref={register({
    required: "required",
    maxLength: {
    value: 15,
          message: "must be max 15 chars",
        },
        validate: (value) => {
          return (
            [/[a-z]/, /[A-Z]/, /[0-9]/].every((pattern) =>
              pattern.test(value)
            ) || "cannot special chars, only lower, upper, number"
          );
        },
      })}
    />
    {errors.email ? <div>{errors.email.message}</div> : null}

Or for example if your field is a password and you want that the user include at least a special character, then it would be like this:

<label htmlFor="password">Password</label>
    <input
      type="password"
      name="password"
      id="password"
      ref={register({
        required: "required",
        minLength: {
          value: 8,
          message: "must be 8 chars",
        },
        validate: (value) => {
          return (
            [/[a-z]/, /[A-Z]/, /[0-9]/, /[^a-zA-Z0-9]/].every((pattern) =>
              pattern.test(value)
            ) || "must include lower, upper, number, and special chars"
          );
        },
      })}
    />
    {errors.password ? <div>{errors.password.message}</div> : null}
  </div>
Carmine Tambascia
  • 1,628
  • 2
  • 18
  • 32
-7

https://regexr.com/

Details documentation RegExp pattern ,

Vinicius Pollo
  • 105
  • 1
  • 3
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31910055) – mc-user Jun 03 '22 at 11:30
  • Lining docs is useless – Yuniac Apr 12 '23 at 20:47