Last updated on July 10, 2023
To perform form validation in React.js using react-material-ui-form-validator
library, you can follow these steps:
Install the required packages:
npm install react-material-ui-form-validator
Import the necessary components and validators in your form component:
import React, { useState } from 'react';
import { TextValidator, ValidatorForm } from 'react-material-ui-form-validator';
import Button from '@material-ui/core/Button';
function MyForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value,
}));
};
const handleSubmit = (event) => {
event.preventDefault();
// Form submission logic
};
return (
<ValidatorForm onSubmit={handleSubmit}>
<TextValidator
label="Name"
name="name"
value={formData.name}
onChange={handleChange}
validators={['required']}
errorMessages={['Name is required']}
/>
<TextValidator
label="Email"
name="email"
value={formData.email}
onChange={handleChange}
validators={['required', 'isEmail']}
errorMessages={['Email is required', 'Email is not valid']}
/>
<TextValidator
label="Password"
name="password"
type="password"
value={formData.password}
onChange={handleChange}
validators={['required', 'minStringLength:8']}
errorMessages={['Password is required', 'Password must be at least 8 characters']}
/>
<Button type="submit" variant="contained" color="primary">Submit</Button>
</ValidatorForm>
);
}
export default MyForm;
In the example above, we create a simple form using the ValidatorForm
component from react-material-ui-form-validator
. Each input field is wrapped with the TextValidator
component, which provides built-in validation functionality.
Configure the validation rules using the validators
prop, and set corresponding error messages using the errorMessages
prop. In the example, we use validators like required
, isEmail
, and minStringLength
with their respective error messages.
Implement the handleChange
function to update the form data state whenever the input values change.
Implement the handleSubmit
function to handle form submission logic. In this example, we prevent the default form submission behavior.
By following these steps, you can utilize the react-material-ui-form-validator
library to perform form validation in your React.js application. Customize the validation rules and error messages based on your specific form requirements.