Form Validation in React (Live Playground)
Form validation is essential for ensuring that users enter valid data in your application. In this tutorial, we'll learn how to add form validation to your React applications with sample code and simple explanations for a variety of validation techniques.
Basic Validation
Let's start with a simple example that demonstrates how to validate a text input to ensure that it is not empty:
import React, { useState } from 'react';
function BasicValidation() {
const [text, setText] = useState('');
const [error, setError] = useState('');
const handleSubmit = event => {
event.preventDefault();
if (text.trim() === '') {
setError('Input cannot be empty');
} else {
setError('');
console.log('Submitted:', text);
}
};
const handleChange = event => {
setText(event.target.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={text} onChange={handleChange} />
{error && <p className="error">{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
export default BasicValidation;
In this example, we validate the text input by checking if it is empty when the form is submitted. If the input is empty, we display an error message using the error
state variable.
Custom Validation Functions
For more complex validation, you can create custom validation functions. Let's create a function that checks if an email address is valid:
function isValidEmail(email) {
const re =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
return re.test(email);
}
Now, let's use this function to validate an email input in our form:
import React, { useState } from 'react';
function EmailValidation() {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
const handleSubmit = event => {
event.preventDefault();
if (!isValidEmail(email)) {
setError('Please enter a valid email address');
} else {
setError('');
console.log('Submitted:', email);
}
};
const handleChange = event => {
setEmail(event.target.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={handleChange} />
{error && <p className="error">{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
export default EmailValidation;
In this example, we use the isValidEmail
function to validate the email input when the form is submitted. If the email is not valid, we display an error message using the error
state variable.
Conclusion
Form validation is an essential aspect of building user-friendly web applications. By learning how to validate user input in your React forms using basic validation, custom validation functions, and error messages, you can create a more intuitive and accessible user experience for your application.