Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex validation?

In a Rails app, I have this current Regex validator below:

validates :characters, format: {with: /\A(([a-z0-9])+(-?[a-z0-9]+)*\s?)+\Z/, message: "can't be blank. Characters can only be [a-z 0-9 . # - +]" }

My validation for Characters initially only allowed lowercase letters and digits. Now I would like to allow for extra characters . # - + how do I structure my Regex now?

like image 305
General_9 Avatar asked May 03 '26 06:05

General_9


1 Answers

As per your question if you want to allow a-z , 0-9 and .#-+ only the regex for that would be:

/[a-z0-9.#+\-]/ and your validation will look something like this:

validates :characters, format: {with: /[a-z0-9.#+\-]/, message: "can't be blank. Characters can only be [a-z 0-9 . # - +]" }

you can even try that out at http://rubular.com/ . imho thats the best place to go for ruby regex.

like image 136
Sahil Dhankhar Avatar answered May 05 '26 21:05

Sahil Dhankhar



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!