DEV Community

Cover image for Form Validation with Material UI Text Field component and React
Anthony Zhang
Anthony Zhang

Posted on • Originally published at Medium

Form Validation with Material UI Text Field component and React

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 component, so it serves as a component equivalent to a integrated with the element.


If we need to set this text field required, we can simply add required={true} as one of our props for , and as we click on the submit button, a warning pops up indicating “Please fill out this field.”,

Divider

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?|[(?:(?:(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? 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

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

Let’s connect:

Github | Medium |

Divider

How can I validate an email address using a regular expression?

Client-side form validation - Learn web development | MDN

Top comments (0)