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.
Here are a couple of samples for different data types:
Custom Error Message
You can customize the error message that is displayed on the form.
Enforce Data Type
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.
Multiple Fields
Of course, you would need to build the validation for multiple fields. These are easy to chain, using commas.
Single Field with Multiple Requirements
Sometimes, you have multiple requirements in a single field. Notice how multiple requirements for a single field are not separated by commas.
Conditional Validation
Sometimes, you need to validate something only where appropriate. This is where a different flavor of syntax is used.
Sometimes, the conditionally required property has multiple requirements.
Regex Pattern Matching
Sometimes, validation requirements are super-specific and require a certain pattern of input. It is easy to pattern match using Regex.
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.
Full structure with multiple validations
Here is the full validation schema for all the fields mentioned above.
I hope these examples now allow you to easily validate your form. Happy Validating!