Form Validation with Material UI Text Field component and React
Tags: webdev, react, mui, form
Published: 2023-12-09 03:31:34

In this article, I will talk about form validation, and how you could use Text Field component in Material UI with React to create a great user experience in form validation.

First of all, what is form validation? Form validation is one of the fundamental features in web development. Client-side validation helps ensure that the data, users submitted to the server side, is in the correct format. It stops the issues from reaching to the server thus saving times back and forth. However, form validation can sometimes be tricky because there are a lot of things to consider during the process.

Below are a few functionalities I found necessary and important to include in the validation process:

 1. **Format Validation**

Format validation is mainly about the use of regular expression. I will not go deep into the concept, but it basically helps restrict the input pattern to match the correct character format in strings. A few common use cases are formats with phone number, email address, mail address and password.

**2. Required**

With `required`, we are able to tell the end users what information we are looking for and remind them with some forms of feedbacks, such as an error message or a popup. This will prevent any submission with missing information.

**3. Feedback**

This is probably the most important part out of these three points. As front end developers, we could write a perfect logic for form validation, but without clear feedback, users could be confused with what to expect and thus results in drop in efficiency. This reminds me of an idea that Steve Jobs mentioned in the WWDC’97,
>  You’ve got to start with the customer experience and work backward to the technology.

I think this is what we should keep in mind as we build web applications.

To start our example, first we need to have our layout ready and import all the required components from Material UI. Here, I use component="form" for the <Box> component, so it serves as a component equivalent to a<div> integrated with the<form> element.
{% gist https://gist.github.com/AnthonyZhang220/93ca21a213097bdcce472061f45c935c.js %}
If we need to set this text field required, we can simply add required={true} as one of our props for <TextField> , and as we click on the submit button, a warning pops up indicating “Please fill out this field.”,

![Divider](https://cdn-images-1.medium.com/max/2000/1*EaKAt9oRC78MemX3mJUNrw.png)

For form validation, we are going to first define the input rules like this,

    const reg = new RegExp("[a-z]");

There are other regex for different purposes, I will include one here for **email** address. (You can easily find other regex rules on the internet)
>  (?:[a-z0–9!#$%&’*+/=?^_`{|}~-]+(?:\.[a-z0–9!#$%&’*+/=?^_`{|}~-]+)*|”(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*”)@(?:(?:[a-z0–9](?:[a-z0–9-]*[a-z0–9])?\.)+[a-z0–9](?:[a-z0–9-]*[a-z0–9])?|\[(?:(?:(2(5[0–5]|[0–4][0–9])|1[0–9][0–9]|[1–9]?[0–9]))\.){3}(?:(2(5[0–5]|[0–4][0–9])|1[0–9][0–9]|[1–9]?[0–9])|[a-z0–9-]*[a-z0–9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

and then we can use test() to test whether the input matches the character combinations in strings, and return true/false. With custom hook in react useState() and form event handler onChange , we can write,

    const [value, setValue] = useState("");
    **const [valid, setValid] = useState(false);**

    const handleValidation = (e) => {
        //set value to user input
        setValue(e.target.value);
        
        //define regex     
        const reg = new RegExp("[a-z]");
        
        //test whether input is valid
        **setValid(reg.test(e.target.value));**
    };
    ...
    <TextField
        name="Name"
        label="Name"
        variant="outlined"
        value={value}
        **onChange={(e) => handleValidation(e)}**
        required={true}
    />

How do we let user know that their input are invalid? <TextField> has another useful prop error , where if we pass in false, it will change the color of the textfield border to red, indicating an invalid input. Here we can simply pass in valid like this,

    <TextField
        name="Name"
        label="Name"
        variant="outlined"
        value={value}
        onChange={(e) => handleValidation(e)}
        **error={!valid}**
        required={true}
    />

If we put in “123” as our input,

![Divider](https://cdn-images-1.medium.com/max/2000/1*LXMwDbfrUN40oVdY9NWOkQ.png)

Voilà! There we have it. A simple form validation with Text Field Material UI and React.

Here is all the code in Code Sandbox: [Demo](https://codesandbox.io/s/magical-joana-ctr9hu?file=/src/App.js)

Let’s connect:

[Github](https://github.com/AnthonyZhang220) | [Medium](https://medium.com/@anthonyzhang220) |

![Divider](https://cdn-images-1.medium.com/max/2000/1*iGeyI4DqMBXD5Kwf0FO_IA.png)

{% cta https://stackoverflow.com/a/201378/6162027 %} How can I validate an email address using a regular expression? {% endcta %}

{% cta https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation %} Client-side form validation - Learn web development | MDN {% endcta %}