Form pattern validation with react-hook-form

user10823960 picture user10823960 · Jul 20, 2020 · Viewed 23.9k times · Source

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.

Answer

anunaki picture anunaki · Jul 20, 2020

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.