Adding Validation (ReactJs)

Adding Validation (ReactJs)

·

1 min read

" entered Age" is actually a string , Not a number . we initialize it to a string here " Line 3 " and anything that's entered into input is always retrieved as a string . That's just how Javascript and the dominance on works. So we have a string here "enteredAge" is a string not a number , Now i'm comparing it to a number here " Line 6" And generally that should work on Javascript , but to be superrrrrrr safe we can force a conversion of " enteredAge " to a number by adding plus (+) here " line 6 "

if (+enteredAge < 1) {      // Line 6
            return;
        }

And with that we ensure that well , it's a number

import React, { useState } from 'react';

const AddUser = (props) => {

    const [enteredAge, setEnteredAge] = useState("");  //  Line 3


    const addUserHandler = (event) => {
        event.preventDefault();

        if (enteredAge < 1) {      // Line 6
            return;
        }
 };


    const ageChangeHandler = (event) => {
        setEnteredAge(event.target.value);
    }



    return (

        <form onSubmit={addUserHandler}>
            <label htmlFor='age'>Age </label>
            <input   id='age'     type="number"  onChange= 
            {ageChangeHandler}/>
           <button type='submit'>Add User</button>
       </form>

    );
}

export default AddUser;