Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow only some characters or empty string in a text field

Tags:

string

regex

null

I am using rexeg to allow only certain characters in a text field. The solution works great however when the field is left blank, the validation throws an error. Basically, I need to allow empty string in a field that is being validated with the below rule:

/^[0-9a-zA-Z,.()+\/\s-]+$/

I tried to put | and |null on different places in the regex rule - in the beginning, in the end, inside or outside the brackets but it does not work. It either allows all characters or still does not allow empty string. Can someone with more knowledge propose a solution please:

like image 892
BradG Avatar asked Oct 21 '25 11:10

BradG


2 Answers

Just replace anchor + (1 or more matches) with * (zero or more matches)

Example:

/^[0-9a-zA-Z,.()+\/\s-]*$/      
like image 52
anubhava Avatar answered Oct 23 '25 03:10

anubhava


Replace the + at the end with a *.

+ means one to infinite repetitions of the previous token

* means zero to infinite repetitions of the previous token

like image 26
Luke Avatar answered Oct 23 '25 03:10

Luke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!