In modern web applications, ensuring that users enter the correct information is crucial for creating seamless and accurate user experiences. React’s controlled components make it straightforward to handle input and validation.
Here’s how to tackle some of the most common form validation types in React, along with examples.
What are Controlled Components?
Controlled components are React components where form input elements’ values are managed by the component’s state. This means that we have total control over the form data and can easily validate it before submission.
Also Read: Mastering Controlled Components in React
Types of Form Validation
- Required Field Validation
- Format Validation
- Length Validation
- Pattern Validation
Let’s go through each of these with examples.
1. Required Field Validation
Required field validation ensures that users don’t leave critical fields empty. This is often done for inputs like names, emails, and passwords.
RequiredField.js
import { useState } from 'react'; const RequiredField = () => { const [name, setName] = useState(''); const [error, setError] = useState(''); const handleNameChange = (e) => { setName(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); if (!name) { setError('Name is required'); } else { setError(''); // Proceed with form submission alert('Form submitted successfully'); } }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={name} onChange={handleNameChange} /> </label> {error && <p style={{ color: 'red' }}>{error}</p>} <button type="submit">Submit</button> </form> ) } export default RequiredField
Explanation
- State: We use useState to store the input value and any error message.
- Validation: When the form is submitted, we check if the name field is empty and show an error if it is.
Output:
2. Format Validation
Format validation ensures that users enter data in the correct format, such as email addresses or phone numbers. React’s controlled components allow us to check formats using regular expressions.
FormatValidation.js
import { useState } from 'react'; const FormatValidation = () => { const [email, setEmail] = useState(''); const [error, setError] = useState(''); const handleEmailChange = (e) => { setEmail(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailPattern.test(email)) { setError('Please enter a valid email address'); } else { setError(''); alert('Form submitted successfully'); } }; return ( <form onSubmit={handleSubmit}> <label> Email: <input type="text" value={email} onChange={handleEmailChange} /> </label> {error && <p style={{ color: 'red' }}>{error}</p>} <button type="submit">Submit</button> </form> ) } export default FormatValidation
Explanation
- State and Regular Expressions: The email pattern regular expression checks that the input matches a standard email format.
- Validation: If the email doesn’t match the pattern, an error message is displayed.
Output:
3. Length Validation
Length validation restricts the number of characters a user can enter, which is useful for fields like usernames or passwords.
LengthValidation.js
import { useState } from 'react'; const LengthValidation = () => { const [username, setUsername] = useState(''); const [error, setError] = useState(''); const handleUsernameChange = (e) => { setUsername(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); if (username.length < 3 || username.length > 15) { setError('Username must be between 3 and 15 characters'); } else { setError(''); alert('Form submitted successfully'); } }; return ( <form onSubmit={handleSubmit}> <label> Username: <input type="text" value={username} onChange={handleUsernameChange} /> </label> {error && <p style={{ color: 'red' }}>{error}</p>} <button type="submit">Submit</button> </form> ) } export default LengthValidation
Explanation
- State: We store the username in state.
- Validation: When the form is submitted, the length of username is checked to ensure it’s within the defined range. If it’s not, an error is shown.
Output:
4. Pattern Validation
Pattern validation checks if the input follows a specific structure, such as a date (YYYY-MM-DD) or a postal code.
PatternValidation.js
import { useState } from 'react'; const PatternValidation = () => { const [postalCode, setPostalCode] = useState(''); const [error, setError] = useState(''); const handlePostalCodeChange = (e) => { setPostalCode(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); const postalCodePattern = /^[0-9]{5}(?:-[0-9]{4})?$/; if (!postalCodePattern.test(postalCode)) { setError('Please enter a valid postal code'); } else { setError(''); alert('Form submitted successfully'); } }; return ( <form onSubmit={handleSubmit}> <label> Postal Code: <input type="text" value={postalCode} onChange={handlePostalCodeChange} /> </label> {error && <p style={{ color: 'red' }}>{error}</p>} <button type="submit">Submit</button> </form> ) } export default PatternValidation
Output:
Explanation
- Pattern Matching: The regular expression ^[0-9]{5}(?:-[0-9]{4})?$ checks for a five-digit code optionally followed by a hyphen and four more digits (e.g., 12345-6789).
- Validation: If the pattern doesn’t match, an error is shown.
Conclusion
These examples cover the basics of form validation using React’s controlled components. Each validation type helps to guide users towards correct input formats, ensuring that your application receives clean and usable data. You can customize these validations for specific needs or combine them to suit more complex forms.
Add comment