DEV Community

Marco Pestrin
Marco Pestrin

Posted on • Updated on

 

Field validator with delay of Material UI input — ReactJS / Javascript

The goal is to have a runtime validation of Material UI Component‘s input with a third part library (Validator).
In our example we will check the phone number with a little trick to handle a delay when we are typing.
We don’t want the errors to come out while we type!

import React, { useState } from 'react';
import isMobilePhone from 'validator/libs/isMobilePhone';
import { TextField } from '@material-ui/core';

export const MyForm = () => {
    const [ phoneNumber, setPhoneNumber ] = useState("");

    const validationPhoneNumber = async(phoneNumber) => {
        let res = false;
        if (phoneNumber !== "") {
            await new Promise((resolve) => setTimeout(resolve, 800));
            res = !isMobilePhone(phoneNumber);
            setErrorPhoneNumber(res)
        }
        return res
    }

    const handleSetPhoneNumber = (event) => {
        setPhoneNumber(event.target.value);
        validationPhoneNumber(event.target.value);
    }
    return (
        <TextField
            fullwidth
            variant="filled"
            label="Phone Number"
            value={phoneNumber}
            error={errorPhoneNumber}
            onChange={(event) => handleSetPhoneNumber}
        />
    )
}
Enter fullscreen mode Exit fullscreen mode

validationPhoneNumber (row 8) is an asynchronous function to handle the delay to check the error. With this logic you have the time to digit and avoid the momentary errors.

First we need to init a variable as false with let because it will be rewritable (row 9). Then we check if our field isn’t empty because as initial state we don’t wanna any type of error (row 10).

In the next line of code we need to stop code execution and wait with a keyword await until the promise is resolved. It will be resolved when the first parameter of setTimeout will be done; in this case after 800 milliseconds. This is one of the many techniques for delaying code execution (row 11).

Then we execute the validation functions that we have imported from the external library and we will save in res if there is an error or not, which is the opposite of the function result (row 12).

In the next line of code we will save in the component state if the error is present. This state will be the error props of TextField component (row 13 and row 28).

Top comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React