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
});
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With