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);
        return res

    const handleSetPhoneNumber = (event) => {
    return (
            label="Phone Number"
            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)