Yup Email Validation: String Schema Code Examples

Last Updated Apr 18, 2022
Elizabeth (Lizzie) Shipton

Lizzie is a Full Stack Engineer at Udacity and freelance technical content writer. She has experience working with Node, GraphQL, Postgres, React and Sass.

Validating emails is an important part of any web application. With Yup email validation, you can ensure that the email address entered by the user is valid. This guide will walk you through how to use Yup email validation with practical code snippets. It will also look at some common problems that can occur when validating emails and alternative methods to using Yup.

A simple email input form with empty initial values

What is Yup?

Yup is a JavaScript schema builder, parser, and validator. You define an object schema, which you can then use to either validate the shape of an existing value or transform an existing value to match the schema. Yup email validation allows you to perform client side validation of emails, passwords, phone numbers, and other form elements.

Yup works with NPM, Yarn and other package managers

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

What is Yup Formik?

Yup and Formik are both packages that can be installed into a React application. Formik is built specifically to work with React, but Yup can be used with any front-end framework. 

Formik is a form-building library. It provides you with out-of-the-box React form elements that can be quickly added to your React app. It takes care of the boilerplate, and automates the repetitive tasks of form-building, like error handling, validation, and visited/required fields.

Formik: a React library for handing form state

Yup is a validation library that can be used in tandem with Formik. Yup provides the schema to validate the form fields you’ve built with Formik. Together, they are a powerful tool for quickly building robust, performant React forms.

Can You Use Yup Without Formik?

Yes, you can use Yup without Formik, and you can use Formik without Yup. However, if you're building a React application, form validation becomes much easier when you use a Formik component and Yup email validation together.

Use Yup, Formik and React together for convenient asynchronous custom validations

Don’t reinvent the wheel, use Abstract’s suite of API tools to successfully validate emails without code.

Yup Email Validation: JavaScript Email Validation Example

Using Yup for email validation is straightforward. Yup provides two email validation methods: the string.email object and the string.matches object. Let’s use a test function to take a look at how to use the very simple string.email() method from the Yup StringSchema.

Using yup.StringSchema.email

The Yup API exports a yup string object that contains a number of methods for validating strings. The yup string email validation function accepts a string input. The Yup object schema provides two methods for validating: isValid and validate.

isValid resolves true if the user submits a valid string, and false if an error exists in the string. validate returns an errors object if the input value is an invalid email. The errors object contains either default error messages or your custom validation message.

Node.js code


import * as yup from 'yup';

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

// check validity
schema
  .isValid({
    email: 'eric.cartman@southpark.com',
  })
  .then((valid) => {
    console.log(valid); // true
  });
schema
  .isValid({
    email: 'not.a.valid.email',
  })
  .then((valid) => {
    console.log(valid); // false
  });

Here, we’re using the basic Yup string email validator to check the validity of an email. We create a yup schema object, passing it the fields we want to include for form validation. We create an email field using the yup.string().email() method.

We then call the Yup isValid function on the schema object, passing it an email string. The isValid function resolves true if the provided email string is valid, or false if it is not.

Comma Separated Email Validation Using Yup

Yup also gives us the ability to validate multiple emails at once, using yup.array. Create a schema with an array field, then define the type of Schema that the array field should expect. In this case, the validator should expect an array of yup string values.

Node.js code


import * as yup from 'yup';

let schema = yup.object().shape({
  array: yup.array().of(yup.string().email()),
});

// check validity
schema
  .isValid({
    array: ['eric.cartman@southpark.com', 'not.a.valid.email'],
  })
  .then(function (valid) {
    console.log(valid); // => false
  });


When you call schema.isValid on a Yup array field, it will only return true if all of the elements in the array are valid. If you call schema.validate() instead, Yup will either return the valid input or throw an error object, which you can then display to users.

Displaying Error Messages

Error messages are a crucial part of UI. It’s important to let your user know when something has gone wrong, and what went wrong.

When it comes to displaying error messages for email validation, Yup provides an easy way to input your own error message. Just pass the message string to the string.email() function. Then, use the schema.validate() method to validate the input.

Node.js code


import * as yup from 'yup';

let schema = yup.object().shape({
  email: yup.string().email('Not a proper email'), // pass your error message string
});

// check validity
schema
  .validate({
    email: 'not.a.valid.email',
  })
  .catch((err) => {
    console.log(err.name); // ValidationError
    console.log(err.errors); // ['Not a proper email']
  });

The schema.validate() function throws an error object with your custom error string when the inputs an invalid email format. Validation errors should be caught and displayed to the user.

Challenges of Verifying with Yup

Unfortunately the Yup library makes a few validation errors. Most notably, it allows invalid email formats.

Yup accepts the following emails as valid:


'eric.cartman@e.c'
'eric.cartman@southpark.com..au'
''

One way around this is to use the yup.string.matches() method instead of the yup.string.email() method, and use custom Regex to match and validate the email addresses.

Alternatives to Yup

Another way around the crucial Yup email validation problem is to use an alternative method to validate emails. One such set of tools is Abstract API’s email validation tools.

Abstract API provides an easy-to-use, language-agnostic API that can be used with JavaScript, Python, Java, Ruby, C, HTML, and many other languages 

Use Abstract’s suite of email validation tools to successfully validate emails without allowing invalid email formats.

Yup Validation FAQs

How Do I Test Validation?

The easiest way to test any validation method is to run your app and pass it some data to validate. You should pass some data that you expect to pass validation, and some that you expect to fail. You should have an expected outcome for each piece of data you input.

Another way to test validation is to write a test module that isolates each validation method and tests it against several valid and invalid inputs. Automate this test module using something like Mocha so that the tests are run every time you add a commit to your code, or at least before you push changes to a remote repository.

What Does Email Validated Mean?

“Email validated” is a message you might see in a UI when the email string that has been input by a user is valid. A valid email includes the ‘@’ symbol and a valid top-level domain such as .com, .edu, .org, etc.

Form validation is a crucial component of most web applications.

What Is Yup Package?

Yup is a JavaScript object schema validator. It's a schema builder and validation package that can be downloaded using a package downloader such as npm or yarn. Once added to your project, you can use it to create schemas that can then be used to either validate input, or cast input to a valid state.

Unfortunately, Yup still has a few kinks to work out, such as accepting invalid emails and empty strings as valid.

What Is Yup Library?

The Yup library is a suite of tools for parsing and validating user input using a custom schema. The most common use-cases for Yup are to validate emails, phone numbers, passwords, and other form fields. Yup is most powerful when used in tandem with a form-builder like Formix or FormBuilder. Together, these libraries take a lot of the repetitive hassle out of building forms.

Don't reinvent the wheel, use Abstract’s suite of API tools to successfully validate emails

Get started for free
Don't reinvent the wheel, use Abstract’s suite of API tools to successfully validate emails
Get started