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:

import React, { useState } from 'react';

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

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.