CUSTOMISED
Expert-led training for your team
Dismiss
How to Validate Email in React.js

30 August 2023

How to Validate Email in React.js

Validating email addresses is an essential part of many React forms. When users submit information through a form on your site, you'll want to ensure the data is valid before sending it to your server. In this article, we'll explore several techniques for validating email addresses in React apps.

JBI Training offers a complete solution to all of your training needs. Speak to us today to find out how we can help or check out our react course 

Why Validate Emails in React?

There are a few key reasons to validate emails on the front-end in React:

  • Improved user experience - Validate emails as users type to provide immediate feedback on any errors. This is better than waiting until submission to inform them of invalid data.
  • Reduce server-side workload - Catch invalid emails earlier to avoid unnecessary API calls with bad data.
  • Safety and security - Validate format to ensure no unsafe strings get passed to back-end.
  • Data integrity - Validate to guarantee emails match expected format before further processing.

Validating in React helps catch issues early and improves the overall form UX.

Built-in HTML5 Validation

The easiest way to validate emails in React is to use built-in HTML5 form validation. The <input type="email"> element will automatically validate the format on supported browsers.

For example:


<input 
  type="email"
  id="email"
/>

This will cause the browser to check that the email field contains a validly formatted email address.

You can access the validation state in React:


const emailInput = document.getElementById('email');

if (emailInput.validity.valid) {
  // email is valid
} else {
  // email is invalid  
}

The limitation of this approach is limited customization for displaying errors. But it's a quick and easy way to get basic email validation in React.

Validating with Regular Expressions

For more flexibility, you can use regular expressions (regex) to validate the email format.

A common regex pattern for validating emails is:


/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|("./.+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

To validate in React:


const validateEmail = (email) => {
  const regex = /valid email regex/;
  return regex.test(email);
}

const email = '[email protected]'; 

if (validateEmail(email)) {
  // email is valid
} else {
  // email is invalid
}

Regex allows matching against more complex email patterns than built-in validation.

Using Validation Libraries

For more complete validation, you can use a form validation library like Formik, React-Hook-Form, or yup.

These libraries provide additional features like:

  • Validation schemas for defining complex validation rules
  • Error message handling and styling
  • Sync/async validation
  • Form submission handling
  • And more...

For example, to validate with yup:


import * as yup from 'yup';

const schema = yup.object().shape({
  email: yup.string().email() 
});

schema.isValid({
  email: '[email protected]'
}).then(valid => {
  // valid is a boolean
});

The schema can validate entire form objects against string, number, and other types of validation rules.

Validation libraries provide the most robust and customizable validation solutions for React.

Writing a Custom validateEmail Function

For maximum flexibility, you can write your own validateEmail function to validate against any patterns you require.

For example:


const validateEmail = (email) => {

  // custom email regex
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (!email || email.length === 0) {
    return 'Email is required'; 
  }

  if (!regex.test(email)) {
    return 'Invalid email format';
  }

  // other custom validations...
  
  return null; 
}

The function can return error messages or throw errors as needed.

Custom validators are useful for specialized email validation requirements.

When to Validate Email

There are two main times to validate emails in React forms:

  1. On form submit
  2. Live as the user types

To validate on submit, attach your validation in the submit handler:


const handleSubmit = (e) => {
  e.preventDefault();
  
  const emailError = validateEmail(email);

  if (emailError) {
    // invalid, display error
  } else {  
    // submit form
  }
}

This will validate the field only when the user attempts to submit the form.

For live validation as the user types, attach to the onChange or onBlur events:


<input
  onBlur={() => {
    const error = validateEmail(email);
    // show error
  }}
/>

This provides real-time feedback as the user edits the field. Keep in mind performance concerns if over-validating.

Displaying Validation Error Messages

A key part of validation in React is displaying user-friendly error messages.

Some best practices for validation error messaging include:

  • Show messages below the invalid field, not just at the top.
  • Use clear, human-readable messages that explain how to resolve.
  • Make sure errors are associated to inputs using aria-describedby for accessibility.
  • Style errors visually to stand out, like with color and icons.

For example:


{errors.email && (
  <p className="error" aria-describedby="email-error">
    {errors.email}
  </p>   
)}

<input
  id="email"
  // other props 
/>

This clearly ties the error to the email input field for better understanding.

Styling and UI Indicators

In addition to error messages, styling and visual indicators can enhance the validation experience.

Some ideas:

  • Show a green/red outline on valid/invalid fields
  • Display a checkmark icon for valid fields
  • Change field border color based on state
  • Disable the submit button for invalid forms
  • Display loading spinners during async validation

For example:


<input
  className={errors.email ? 'invalid' : 'valid'} 
/>

<style>
.invalid {
  border: 1px solid red;
}

.valid {
  border: 1px solid green;  
}
</style>

Good validation UI provides clarity to your users as they fill out forms.

Making Validation Accessible

When validating forms, don't forget accessibility principles. Some tips:

  • Use ARIA attributes like aria-invalid and aria-describedby to convey validation status to screen readers.
  • Make sure color contrast meets minimum ratios for users with visual impairments.
  • Provide multiple ways to convey information, like colors, text, and icons together.
  • Allow keyboard navigation and screen reader focus to errors.

For example:


<input
  aria-invalid={errors.email ? 'true' : 'false'}
  aria-describedby="email-error-message" 
/>

<div id="email-error-message" className={errors.email ? 'show' : 'hide'}>
  {errors.email}   
</div>

This provides multiple levels of context about the error to users of assistive technologies.

Summary and Recap

A quick summary of key points:

  • Validate emails to improve UX, reduce server workload, and ensure data integrity.
  • Leverage built-in HTML5 validation for quick wins.
  • Use regex or validation libraries like Formik for robust validation.
  • Write custom functions for maximum flexibility.
  • Validate on submit and as user types for best UX.
  • Clearly communicate errors and style fields to reveal state.
  • Follow accessibility guidelines.

Email validation is critical for professional React forms. Start with built-in and regex validation, then explore libraries for complex needs. Focus on the user experience and communicate errors clearly at every step.

Frequently Asked Questions

How do I validate emails in React Native?

React Native includes the same built-in email input validation. You can also use regex or validation libraries like Formik.

Should I validate on the client vs. server?

Validate on both! Client-side validation provides immediate user feedback, while server-side ensures safety before processing.

What if emails are validated asynchronously?

Display a loading indicator while validating, disable the submit button, and show errors when the promise resolves.

How can I customize error messages?

Use custom validator functions to return any error messages needed for your forms.

What validation library works best with React?

Formik is quite popular, but also consider React Hook Form, yup, and others. Try a few to see what fits your needs.

Resources and Next Steps

Here are some resources for further learning:

Next steps to apply what you've learned:

  • Add validation to an existing form in a React project
  • Build a reusable custom validation hook
  • Implement a multi-step form flow with complex validation
  • Explore integrating with a form backend like Formspree
  • Read the source code for validation libraries like Formik

Hopefully this article has provided a good overview of how to validate emails and other inputs within React applications. Validating properly improves the user experience and data quality of any web form.

Check out our next article react how to trigger rerender we will be adding a series of articles taken from our react course

Amidst today's ever-evolving realm of dynamic web development, React.js emerges as an indispensable asset for both frontend engineers and developers. Its capacity to construct dynamic user interfaces paves the way for engaging user experiences and streamlined development processes.

Whether you're embarking on your journey into React.js or seeking to refine an existing skill set, our comprehensive training modules at JBI Training are poised to facilitate your mastery of this powerful library. Don't hesitate; embrace the potential of React.js to revolutionize your web development workflows today.

Embark on your educational voyage now with the React.js courses at JB International and unlock the vast potential of dynamic web development. Our offerings include:

1. React: Tailored for individuals new to React.js, this course covers the essentials of React.js development. Learn about components, JSX syntax, state management, and the React lifecycle. Acquire the skills needed to create interactive and efficient user interfaces.

2. React Native: Dive into the world of mobile app development using React Native. Discover how to build cross-platform mobile applications using the power of React.js. Learn to create native-like experiences for iOS and Android platforms with a single codebase.

3.Reactive Extensions Rx*: Explore the paradigm of reactive programming with Rx. Learn how to manage asynchronous data streams and events using RxJS. Discover how to compose and transform streams, enabling you to build responsive and interactive applications.

4. Typescript: Elevate your frontend development skills with TypeScript. This course introduces you to TypeScript's static typing, interfaces, and advanced type features. Gain confidence in writing more robust and error-free JavaScript code.

5.Typescript - Beyond the Basics: Take your TypeScript expertise to the next level. Dive deeper into advanced type patterns, decorators, and integration with frontend frameworks. Learn to architect scalable and maintainable applications with TypeScript.

Enrol in these courses and embark on a transformative journey to harness the power of React.js and related technologies. Equip yourself with the tools and knowledge needed to create dynamic, responsive, and cutting-edge web and mobile applications.​​​​​​

 

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course