Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react form validation

const {
  handleSubmit, // handles form submission
  handleChange, // handles input changes
  data, // access to the form data
  errors, // includes the errors to show
} = useForm({ // the hook we are going to create
  validations: { // all our validation rules go here
    name: {
      pattern: {
        value: '^[A-Za-z]*$',
        message:
          "You're not allowed ...",
      },
    },
  },
  onSubmit: () => alert('User submitted!'),
  initialValues: { // used to initialize the data
    name: 'John',
  },
});

// ...
return (
  <form onSubmit={handleSubmit}>
    <input value={data.name || ''} onChange={handleChange('name')} required />
    {errors.name && <p className="error">{errors.name}</p>}
    {/** ... */}
  </form>
);
Source by felixgerschau.com #
 
PREVIOUS NEXT
Tagged: #react #form #validation
ADD COMMENT
Topic
Name
4+1 =