0

I am using a validation to reject any string containing <p> or &lt;p&gt; (equivalent in html characters of the p html tag).

I tried with a string that did contain it and strings with <p> tag are rejected but not those with &lt;p&gt;

validates_format_of :message_content,
                      :with => /\A((?!<p>).)*\z/i,
                      :message => "pb1"             


validates_format_of :message_content,
                      :with => /\A((?!&lt;p&gt;).)*\z/i,
                      :message => "pb2"  

Should I escape some of the special characters of !&lt;p&gt; ,which could create issues for the regexp ? How ?

9
  • how about using a custom validator and gsubbing the escaped html entities before performing the regex? Commented Dec 12, 2017 at 16:29
  • 1
    Is this a rails question? If so tag it appropriately. Commented Dec 12, 2017 at 16:31
  • 1
    I see no need for escaping characters. Doesn't r = Regexp.new("<p>|&lt;p&gt;") #=> /<p>|&lt;p&gt;/ work (i.e., str !~ r)? Commented Dec 12, 2017 at 16:55
  • 1
    I think you should take a different approach using the sanitize helper. Insert something like before_validation :sanitize_content, :on => :create and then in your sanitize_content method use ActionController::Base.helpers.sanitize(field, tags) configured appropriately. Your meager attempt at preventing p tags is easily fooled (e.g. by whitespace < p>) Commented Dec 12, 2017 at 17:50
  • 1
    ^^ This. I'm 95% sure you're asking the wrong question here. Trying to block HTML input via a regex validation screams of bad design; there's almost certainly a better solution to your problem. Commented Dec 12, 2017 at 17:52

1 Answer 1

2

You can try to validate that a regexp is not match. You will have simplier regexp that are easier to implement :

validates :message_content, format: { without: /<p>/i, message: 'pb1' }
validates :message_content, format: { without: /&lt;p&gt;/i, message: 'pb2' }
Sign up to request clarification or add additional context in comments.

Comments

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.