How can I validate a form when I am using React as the frontend?
- User
How can I validate a form when I am using React as the frontend?
Assistant
Here are a few common ways to validate forms when using React:
- Use client-side validation with onSubmit handler:
jsxconst App = () => { const handleSubmit = (e) => { e.preventDefault(); // validate form fields if(valid) { // submit form } } return ( <form onSubmit={handleSubmit}> // form fields </form> ) }- Validate fields onChange:
jsxconst handleChange = (e) => { // validate field setFieldError(validate(e.target.value)) }- Use a validation library like Yup or Joi:
jsximport * as yup from 'yup' const schema = yup.object({ name: yup.string().required(), email: yup.string().email() }) const handleSubmit = async (values) => { try { await schema.validate(values) // submit form } catch (err) { // validation error } }