Validating form input is crucial for accurate data and a smooth user experience. In React, uncontrolled components let the DOM manage form data, making certain validations simpler to handle without React state.
Also Read: Mastering Uncontrolled Components in React
Here, we’ll cover:
- Required Field Validation
- Format Validation
- Length Validation
- Pattern Validation
With clear examples and explanations, you’ll be ready to implement these validations for any React form.
1. Required Field Validation
The goal of required field validation is to ensure the user doesn’t leave essential fields empty. With uncontrolled components, we can use HTML’s required
attribute to handle this for simple inputs.
Example:
RequiredField.js
import React, { useRef } from 'react'; const RequiredField = () => { const nameRef = useRef(); const handleSubmit = (e) => { e.preventDefault(); if (nameRef.current.value === '') { alert('Name is required.'); } else { alert(`Form submitted! Name: ${nameRef.current.value}`); } }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" ref={nameRef} required /> </label> <button type="submit">Submit</button> </form> ) } export default RequiredField
Here, we set the required
attribute on the input, which will prevent form submission if the field is empty. We also use JavaScript to show a custom message if the field is left blank.
Output:
2. Format Validation
Format validation checks that the input follows a specific structure, like an email address. For uncontrolled components, you can use regular expressions or built-in HTML input types, such as type="email"
for email validation.
Example:
FormatValidation.js
import React, { useRef } from 'react'; const FormatValidation = () => { const emailRef = useRef(); const handleSubmit = (e) => { e.preventDefault(); const emailValue = emailRef.current.value; if (!/\S+@\S+\.\S+/.test(emailValue)) { alert('Please enter a valid email address.'); } else { alert(`Form submitted! Email: ${emailValue}`); } }; return ( <form onSubmit={handleSubmit}> <label> Email: <input type="email" ref={emailRef} /> </label> <button type="submit">Submit</button> </form> ) } export default FormatValidation
In this example, we’re using a regular expression in JavaScript to validate the email format. The type="email"
attribute also assists by ensuring the field only accepts email-formatted input.
3. Length Validation
Length validation restricts input based on a minimum or maximum number of characters. This is useful for fields like usernames or passwords.
Example:
LengthValidation.js
import React, { useRef } from 'react'; const LengthValidation = () => { const usernameRef = useRef(); const handleSubmit = (e) => { e.preventDefault(); const usernameValue = usernameRef.current.value; if (usernameValue.length < 5 || usernameValue.length > 15) { alert('Username must be between 5 and 15 characters.'); } else { alert(`Form submitted! Username: ${usernameValue}`); } }; return ( <form onSubmit={handleSubmit}> <label> Username (5-15 characters): <input type="text" ref={usernameRef} /> </label> <button type="submit">Submit</button> </form> ) } export default LengthValidation
Here, JavaScript checks if the username length is within the 5-15 character range. If not, a message is shown to the user.
4. Pattern Validation
Pattern validation checks if the input follows a custom format using regular expressions. For example, a ZIP code or phone number format.
Example:
PatternValidation.js
import React, { useRef } from 'react'; const PatternValidation = () => { const zipCodeRef = useRef(); const handleSubmit = (e) => { e.preventDefault(); const zipCodeValue = zipCodeRef.current.value; const zipCodePattern = /^[0-9]{5}(?:-[0-9]{4})?$/; // US ZIP code pattern if (!zipCodePattern.test(zipCodeValue)) { alert('Please enter a valid ZIP code (e.g., 12345 or 12345-6789).'); } else { alert(`Form submitted! ZIP Code: ${zipCodeValue}`); } }; return ( <form onSubmit={handleSubmit}> <label> ZIP Code: <input type="text" ref={zipCodeRef} /> </label> <button type="submit">Submit</button> </form> ) } export default PatternValidation
In this example, we use a regular expression to enforce the ZIP code format. This will alert the user if their input doesn’t match the pattern.
Conclusion
These examples demonstrate the essentials of form validation using uncontrolled components in React.
By combining HTML attributes and JavaScript checks, you can effectively validate user input without needing to rely on React state, making it simpler and faster for certain forms.
Add comment