3

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?

2
  • 1
    What exactly are you validating? Also, your regex matches an optional - as well as an optional space. Commented Aug 18, 2013 at 13:58
  • So you mean that ######## is also valid? Commented Aug 18, 2013 at 14:21

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can always use \d instead of 0-9.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.