How to validate Mui TextField email in Next.js

Cover Image for How to validate Mui TextField email in Next.js
Ali Bentaleb

In this tutorial, we are going to explain how to validate a material UI (MUI) email textfield in a React based app like Next.js

The steps are :
  • Install MUI and validator

  • Create textField

  • Validate email textField with a submit button

Now, let’s start

Material UI (MUI) textfield

Meterial UI (MUI) Text field is an html input where the user can enter and edit text.

To install it use:

## npm

npm i @emotion/styled @emotion/react @mui/material validator

##yarn

yarn add @emotion/styled @emotion/react @mui/material validator

MUI textfield validation email

Next, to validate MUI textfield validation email, you need to :

  • Use isEmail function from validator , this is a popular package on npm and it checks whether the typed email is a syntax correct email.

  • if the typed email is syntax OK then we inform the user that the email is OK, otherwise we inform the user that the email is a not OK.

Now let’s see how we can do it with our e-mail text field validation example

Create pages/test.js and copy the following code

import {Button, TextField} from '@mui/material';
import {useState} from 'react';
import isEmail from 'validator/lib/isEmail';

export default function Test() {
	const [email, setEmail] = useState('');

	return (
		<form className="p-2 flex flex-col w-1/3">
			{' '}
			<TextField
				id="someId"
				label="Email"
				onChange={(e) => setEmail(e.target.value)}
			/>
			<Button
				size="large"
				variant="contained"
				style={{backgroundColor: 'black'}}
				onClick={() =>
					isEmail(email)
						? alert('email is valid')
						: alert('email is not valid')
				}
			>
				Submit
			</Button>
		</form>
	);
}

Test validation

Now when you run localhost:3000/test and type in a.b@c.com for example and click on submit

You should see an alert telling you that the email is OK

mui email textfield validation

You can try it live as well with a wrong email address, for example a@b email textfield validation

The email is stored on our React state which will be then passed to isEmail function as a parameter

The isEmail function is a great tool to check against the typed email, so it makes all the necessary checks like if arobase exists, if the domain name exists and so on

If everything is Ok , we display a good result, otherwise we tell the user that the email is not a valid email

Conclusion

We have seen how to validate a mui textfield validation email in quick steps.

If you like to work with mui, check also this article which will help you understand how to validate a textfield and change textfield input CSS based on user input, for example if the user typed a wrong text or left the field empty to surround the field with red.

How to make readonly mui textf...How to use nivo charts with Ne...