Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup schema validation: Exclude a certain pattern in the method '.matches()'

I want to make sure users don't fill in their username (pattern is a upercase or lowercase u, followed by 7-10 digits: U0000000)

In the following example, the regex itself does work. However in conjunction with the .matches() method it does not validate the field.

const schema = Yup.object()
  .shape({
    myField: Yup.string()
      .matches(/.*\d/, 'Should contain a digit') // <- this works
      .matches(/(?!.*[uU]\d{7,10})/, 'Should not contain a user ID') // <- this does not
  });
like image 746
Remi Avatar asked Dec 10 '19 13:12

Remi


People also ask

What is Yup schema validation?

What is Yup? Yup is a JavaScript object schema validator. Lets understand the above definition with an example. Consider everday common feature of login form with fields "username" and "password". Before submitting form we want to verify that user has entered all fields.

What is Yup schema?

Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformations.

What is Yup Object () shape?

yupobject documentation. Basically passing the schema to shape is just the long-form of passing it to the object constructor. Shape does however offer the benefit of chaining and overloading definitions in later chained methods. See yup.shape documentation. Follow this answer to receive notifications.


1 Answers

Turns out that matches will only validate an invalid error if the Regex you provide returns positive.

If you want to validate on a negative 'match' (a.k.a. not operator regex match), you can use the .test() method.

In the documentation it's not mentioned under string, but under mixed (source):

mixed.test(name: string, message: string | function, test: function): Schema

So in my example I ended up with:

const containsDeviceId = (string) => /d\d{7,10}/.test(string);
const schema = Yup.object()
  .shape({
    myField: Yup.string()
      .matches(/.*\d/, 'Should contain a digit')
      .test(
        'Should not contain a user ID',
        'Should not contain a user ID',
        (value) => !containsDeviceId(value)
      ),

Hope this helps someone.

like image 108
Remi Avatar answered Sep 19 '22 01:09

Remi