Written by: Geoffrey Callaghan
Simple React Validator
Simple React Validator
Simple React Validator is a straightforward validation library for React applications. It offers an easy-to-use interface for adding validation rules to your forms. This tutorial will guide you through the process of setting up and using Simple React Validator in a React project.
First, ensure you have a React project set up. If you don’t have one, you can create a new React application using Create React App:
npx create-react-app my-simple-react-validator-app
cd my-simple-react-validator-app
Install Simple React Validator using npm or yarn:
npm install simple-react-validator
# or
yarn add simple-react-validator
Here’s a simple example to demonstrate how to use Simple React Validator for form validation in a React component.
First, import Simple React Validator in your component:
import React, { useState } from 'react';
import SimpleReactValidator from 'simple-react-validator';
Next, create a form component and initialize the validator instance:
const MyForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
});
const validator = new SimpleReactValidator();
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
if (validator.allValid()) {
alert('Form is valid!');
// Handle form submission here
} else {
validator.showMessages();
// Force a re-render to display validation messages
setFormData({ ...formData });
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
onBlur={() => validator.showMessageFor('name')}
/>
{validator.message('name', formData.name, 'required|alpha_space')}
</div>
<div>
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
onBlur={() => validator.showMessageFor('email')}
/>
{validator.message('email', formData.email, 'required|email')}
</div>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
You can customize the validation messages by passing a messages object to the SimpleReactValidator constructor.
const validator = new SimpleReactValidator({
messages: {
required: 'This field is required',
email: 'Please enter a valid email address',
alpha_space: 'Only alphabetic characters and spaces are allowed',
},
});
Simple React Validator supports a wide range of validation rules and allows you to create custom validation rules.
You can use various built-in validation rules provided by Simple React Validator. Here are a few examples:
{validator.message('username', formData.username, 'required|alpha_num_dash')}
{validator.message('age', formData.age, 'required|integer|min:18')}
{validator.message('password', formData.password, 'required|min:6|max:20')}
To create custom validation rules, you can extend the SimpleReactValidator prototype:
SimpleReactValidator.addLocale('custom', {
min: 'The :attribute must be at least :min characters.',
});
const validator = new SimpleReactValidator({
locale: 'custom',
validators: {
customPassword: {
message: 'The :attribute must contain at least one uppercase letter, one lowercase letter, and one number.',
rule: (val) => {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/.test(val);
},
messageReplace: (message, params) => message.replace(':attribute', params[0]),
},
},
});
Then, use the custom validation rule in your form:
{validator.message('password', formData.password, 'required|customPassword')}
The validation messages are displayed using the message
function. You can customize how and where the messages are displayed:
<div>
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
onBlur={() => validator.showMessageFor('email')}
/>
<div className="error">
{validator.message('email', formData.email, 'required|email')}
</div>
</div>
Simple React Validator is an easy-to-use library for adding form validation to your React applications. This tutorial covered the basics of setting up and using Simple React Validator, customizing validation messages, and creating custom validation rules. For more advanced usage and detailed documentation, refer to the official Simple React Validator documentation.