Validate an input in React

To validate an input form in React—to validate emails, numbers, passwords, etc.—you can use the type property.

For example, let's see how to validate an email as input:

jsx
import React, { useState } from 'react';

const ValidateInput = () => {
    
    const [email, setEmail] = useState('');
    
    const handleInput = (e) => {
        
        setEmail(e.target.value);
        
    }
    
    const submit = (e) => {
        
        e.preventDefault();
        
        console.log(`${email} submited!`);
        
    }
    
    return(
        <form onSubmit = {submit}>
            <input type = 'email' placeholder = {'Write your email...'} onChange = {handleInput}/>
            <button>Send</button>
        </form>
    );
    
}

export default ValidateInput;

Remember that, instead of calling the submit function from the button, you call it from the form block. Don't forget to call e.preventDefault() from the submit function. Otherwise, the function won't execute because the default action of a form is a GET method.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.