0

In my rails model I have some kind of template system. I want to make sure that users editing it do not make accidental mistakes so I use some simple validators.

They can use markers like ##user_id## that will be replaced later. I want to make sure they do not enter something like ###user_id## that contains too many #, so not any ### (or ####) must appear in the field.

class Template
  validates_format_of :text, :with => /##user_id##/, 
    :message => "##user_id## must be present"
  validates_format_of :text, :not_with => /###/, 
    :message => "Too many #"
end

Unfortunately there is no :not_with option ... is there any chance to solve it using a :with-regex or should I go a separate validate method?

I tried some negative look-ahead, but as there are (mostly) several ## and only one ### they always match one of them.

3 Answers 3

4

Use the :without option:

validates_format_of :text, :without => /###/, :message => "Too many #"
Sign up to request clarification or add additional context in comments.

Comments

1

What about this...

validates_format_of :text, :with => /(^|[^#])##user_id##($|[^#])/

EDIT: I copied acheong87's rubular examples with my regex.

Comments

0

Can you do something like this?

    /^(.(?!###+user_id##|##user_id###+))*$/

Here's a live demo: http://rubular.com/r/SPwsyDlj0y.

In (more) English, it says,

A string in which no character is followed by ###+user_id## or ##user_id###+.

1 Comment

This is some kind of query I tried before, but unfortunately it is not working with the validates_format_of

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.