Getting email validation right in Material-UI is fundamental for clean data and a good user experience. You'll find five distinct methods for setting it up, each with working code. We'll also look at the drawbacks of these traditional approaches and how Abstract API solves them.
How to Implement Email Validation in MUI
Here are four distinct methods to set up email validation in your Material-UI forms. Each approach has a different implementation, from native browser features to popular validation libraries.
Browser-Level Validation via MUI TextField
This method leverages the fact that the MUI `TextField` component forwards its props to the underlying HTML "input" element. By setting the "type" attribute to "email", you activate the browser's built-in validation logic.
The validation state is checked on the `onBlur` event, which fires when the user moves focus from the field. The input's `validity.valid` property reports if the content is a valid email format according to the browser's rules.
This boolean value then toggles MUI's "error" prop. The "helperText" prop can display a message like 'Invalid email' when an error exists. This approach provides zero-cost validation and works without extra libraries.
<TextField type="email" required onBlur={e => setError(!e.target.validity.valid)} error={error} helperText={error && 'Invalid email'} />
Custom HTML Pattern with the Native Validity API
To enforce stricter rules, you can add a custom pattern to the browser's native validation. This is done through the `TextField`'s "inputProps" prop, where you supply a regular expression to the "pattern" key.
For example, you could require that all emails belong to a specific domain. The browser evaluates the input against this pattern. The rest of the implementation remains the same as the previous method.
You still use the `onBlur` event and the `validity.valid` property to control the "error" and "helperText" props in MUI. This pushes pattern evaluation to the browser's engine.
<TextField label="Work e-mail" required inputProps={{pattern:'^[A-Za-z0-9._%+-]+@mycorp\\.com$'}} onBlur={e=>setError(!e.target.validity.valid)} … />
Schema Validation with Formik and Yup
This approach combines the Formik library for form state management with Yup for schema-based validation. You define all your validation rules, such as requiring an email format, inside a central Yup schema object.
Formik uses this schema to validate the form's values. It provides "errors" and "touched" objects that track the validation status of each field. This method centralizes form state and rules.
The MUI `TextField` is then connected to Formik's state. The "error" prop is set based on whether a field has been touched and has an error, while "helperText" displays the specific error message from Yup.
const schema = Yup.object({ email: Yup.string().email().required() });
<Formik initialValues={{email:''}} validationSchema={schema} onSubmit={…}>
{({errors,touched})=>(
<TextField name="email" value={values.email} onChange={handleChange} error={touched.email&&Boolean(errors.email)} helperText={touched.email&&errors.email}/>
)}
</Formik>
Controlled Component with a Runtime Validator
This technique creates a fully controlled component where React manages all state. You use the `useState` hook to hold the input's current value and a separate boolean for its error status.
The `onChange` event handler updates the email's value in the state. It also runs a validation function, for instance from a library like "validator.js", on every keystroke to check the new value.
The function's result immediately updates the error state. This state is then passed to the `TextField`'s "error" and "helperText" props, making the entire validation process run inside React.
import isEmail from 'validator/lib/isEmail';
const [email,setEmail]=useState(''); const [err,setErr]=useState(false);
<TextField value={email} onChange={e=>{const v=e.target.value; setEmail(v); setErr(!isEmail(v));}} error={err} helperText={err&&'Invalid email'}/>
Challenges of Email Validation in MUI
These traditional methods introduce significant reliability and consistency problems. The component's design, combined with browser quirks, creates hidden pitfalls that can easily compromise your forms and the user experience.
- The custom HTML pattern method fails because the MUI TextField does not pass the pattern attribute to the input element. This makes advanced regex checks fragile and forces complex workarounds that undermine your form's declarative logic.
- Browser-level validation via type="email" defers to inconsistent browser rules. An address Chrome accepts might fail in another client. This makes validation success dependent on the user's browser, not your application's logic.
- Controlled components that use onChange face state synchronization issues. Browser features like autofill can update the input value without a change event. This leaves your React state out of sync with the actual user input.
- Client-side validation, whether with regex or libraries like Yup, cannot handle all valid email formats like internationalized domains. The only trustworthy check is a confirmation email, which makes any client-side flag inherently unreliable.
Validate Emails with Abstract API
Add reliable email validation to your MUI forms to prevent bad sign-ups and improve data quality.
Get started for free
How Abstract API Handles Email Validation in MUI
Unlike traditional methods, Abstract API addresses the core weaknesses of email validation in MUI through a fast, multi-layered check.
- It performs layered validation that includes syntax checks, typo corrections, and a blacklist of over 3,000 disposable domains. The API also executes an SMTP handshake, an MX lookup, and catch-all detection, all within milliseconds.
- The API returns a single JSON payload that indicates deliverability status and a quality score. It also provides booleans for disposable domains, MX records, and SMTP validity, which allows for a simple check inside your component.
- Because the complex work occurs on the server, your React bundle remains lean. You simply send a GET request and interpret the response. Rate-limited free keys support local development, and SOC 2/GDPR compliance removes security concerns.
How to Set Up Abstract API in Your Project
Once you know Abstract’s capabilities, the addition of its email validation API to your project is simple.
- Sign up at Abstract API and copy your Email Validation API key. The free tier is sufficient for development.
- Install axios with npm or use the native fetch API inside your React/MUI workspace.
- Add your key to a ".env" file as "REACT_APP_ABSTRACT_KEY" and restart the development server.
- Create a utility file, for example "src/utils/emailValidator.js", with a function that calls the API endpoint.
- In your MUI form, call the validation function inside the TextField "onBlur" event. If the result's "deliverability" property is not "DELIVERABLE", set the error state and helper text.
- For deployment, the key can remain as an environment variable on your CI/CD platform, so no code change is required between environments.
Sample Email Validation Implementation with Abstract API
The code below shows a functional React component that uses an MUI TextField. When a user leaves the input field, the "onBlur" event triggers a call to Abstract API. The component then uses the API response to set an error state or display a correction suggestion in the helper text.
import { useState } from 'react';
import TextField from '@mui/material/TextField';
import axios from 'axios';
async function validateEmail(email) {
const url = `https://emailvalidation.abstractapi.com/v1/?api_key=${process.env.REACT_APP_ABSTRACT_KEY}&email=${encodeURIComponent(email)}`;
const { data } = await axios.get(url);
return data;
}
export default function EmailField() {
const [email, setEmail] = useState('');
const [error, setError] = useState(false);
const [helper, setHelper] = useState('');
const handleBlur = async () => {
const res = await validateEmail(email);
if (res.autocorrect) setHelper(`Did you mean ${res.autocorrect}?`);
setError(res.deliverability !== 'DELIVERABLE' || res.is_disposable_email.value);
};
return (
<TextField
label="Email"
value={email}
onChange={e => setEmail(e.target.value)}
onBlur={handleBlur}
error={error}
helperText={helper}
fullWidth
/>
);
}
The API returns a JSON object with detailed validation results. Here is a sample response:
{
"email": "johnsmith@gmail.com",
"autocorrect": "",
"deliverability": "DELIVERABLE",
"quality_score": 0.9,
"is_valid_format": { "value": true },
"is_free_email": { "value": true },
"is_disposable_email": { "value": false },
"is_role_email": { "value": false },
"is_catchall_email": { "value": false },
"is_mx_found": { "value": true },
"is_smtp_valid": { "value": true }
}
The "deliverability" and "quality_score" fields drive the primary validation decision. The "autocorrect" field provides a suggested fix for typos, which you can show to the user. Additional booleans permit more granular control, such as the block of disposable emails or a flag for catch-all addresses for later review.
Final Thoughts
Standard email validation in MUI often misses typos, disposable domains, and other deliverability issues because it relies on simple syntax checks. Abstract API solves this with its fast, multi-layered server-side analysis.
For more robust forms, consider the creation of an account on Abstract API to get your free API key and reliably validate user emails.
Validate Emails with Abstract API
Don't let invalid emails compromise your data. Add proper email validation to your MUI app.
Get started for free