Open In App

How to handle data validation with React Hooks ?

Data validation is a critical component of software development that ensures the accuracy, consistency, and suitability of the data that is being processed or stored in a system. It involves implementing checks and constraints to ensure that the data meets certain criteria or standards.

Key Points for Data Validation with React Hooks:

Example: Below is an example of handling data validation with Hooks.




import React, {
    useState,
    useEffect
} from 'react';
 
const App = () => {
    const [name, setName] = useState('');
    const [isValidName, setIsValidName] = useState(true);
 
    const handleChange = (event) => {
        const value = event.target.value;
        setIsValidName(value.length >= 3);
        setName(value);
    };
 
    useEffect(() => {
 
        if (name === 'admin') {
            alert('Admin name is not allowed!');
        }
    }, [name]);
 
    return (
        <div>
            <input
                type="text"
                value={name}
                onChange={handleChange}
                style={{
                    borderColor:
                        isValidName ? 'initial' : 'red'
                }}
            />
            {!isValidName &&
                <p>Name should be at
                    least 3 characters long.
                </p>}
        </div>
    );
}
 
export default App;

Output:

Output


Article Tags :