Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup validation with regex using matches problem

So I have below validation using Yup :

const myValidtion = yup
.string()
.trim()
.matches(/[abcdefghijklmnopqrstuvwxyz]+/ , 'Is not in correct format')
.required();

So with this, this will pass : hello world as expected. But what make me confused is why this also will pass : hello WORLD or this also pass : hello ,&$#$ world

In other hand, if we only enter invalid chars like *%$&#$($# this will not pass and show me the error. So as I can see, this only give me the error if ALL the entry is invalid.

What I'm looking is how to use Yup matches method to NOT pass if user enter for example : hello ,*&) world

Can anyone help me with this?

like image 960
Emad Dehnavi Avatar asked Jan 28 '19 16:01

Emad Dehnavi


1 Answers

Your regex should cover your whole string, by using ^ and $ to signify start and end of string:

/^[abcdefghijklmnopqrstuvwxyz]+$/

Otherwise, it will match part of your string, which is why it matches when you have a mix of good and bad characters, but fails when every character is bad.

You can shorten the regex by using a character range like this:

/^[a-z]+$/

You can use this online tool to build and test your regex.

like image 96
jo_va Avatar answered Sep 30 '22 19:09

jo_va