Yup is a schema validation library. One would use it to add property validations that execute prior to form submission. It is also pretty easy to use, it’s just difficult to find concrete examples to model off of.

Because of this difficulty in finding good examples that showcase its syntax, I’ve compiled some common examples in Javascript.

 

Schema Structure

First, you need to know the basic structure to use.

Sample: Structure of schema validation

Here are a couple of samples for different data types:

Sample: First name is required

Sample: Birth Date is required

 

You can customize the error message that is displayed on the form.

Sample: Custom error message for first name

 

You can also enforce that the data entered in the field corresponds to a particular data type. You can specify a particular message to be displayed when the value entered is not a real date.

Sample: Birth Date value has to be a date

 

Of course, you would need to build the validation for multiple fields. These are easy to chain, using commas.

Sample: First name and last name are both required

 

Sometimes, you have multiple requirements in a single field. Notice how multiple requirements for a single field are not separated by commas.

Sample: Birth Date is required and cannot be in the future

 

Sometimes, you need to validate something only where appropriate. This is where a different flavor of syntax is used.

Sample: When you chose to pay with a credit card, then the expiration date is required

Sometimes, the conditionally required property has multiple requirements.

Sample: When you chose to pay with a credit card, then the expiration date is required, cannot be in the past, and has to be a real date

 

Sometimes, validation requirements are super-specific and require a certain pattern of input. It is easy to pattern match using Regex.

Sample: Using regex to pattern match

 

 

In conclusion, these sets of examples should be a good launching point to get Yup validation implemented. The syntax is easy to use once you know what structure the validator is looking for.

It is also apparent that you can get pretty complex for what you need on the form.

 

Here is the full validation schema for all the fields mentioned above.

Sample: Full validation schema containing all of the fields validated above

I hope these examples now allow you to easily validate your form. Happy Validating!