Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - HTML5 Validate Text input using pattern containing quote

This is not one of these "help me build my regex" questions. I have an HTML form input field where a user can provide geographical position data in various formats. The following regex works fine in regexr.com as well as in my application. However, I want to use the "pattern" parameter of HTML5 to additionally validate a user's input before submitting it.

((([E|W|N|S](s)?)?([-]?[0-1]?[(0-9)]{1,2})[°][ ]?([(0-5)]?[(0-9)]{1})([.|,][0-9]{1,5})?['][ ]?([0-5]{0,1}[0-9]?(([.|,])[0-9]{0,3})?)(["]|[']{2}){0,1}((s)?[E|W|N|S])?)|([-]?[1]?[0-9]{1,2}[.|,][0-9]{1,9}))

The point is that this regex contains a quote character ("). Now, I put this regex in my input like this:

<input type="text" pattern = "regex..."...." />

Browsers do not recognize this regex and don't do any validation at all, so obviously I need to escape that quote. What I tried so far:

  • PHP's addslashes() function escapes too many characters.
  • I escaped the quote with a single backslash

That did not change anything. I tested with Chrome, which works fine with simple regular expressions. The one above obviously is a bit too complicated.

I know the regular expression above is not perfect for matching coordinates, however, this is not to be discussed here. I just would like to know how to correctly escape a pattern in HTML5 as Chrome does not do anything with that regex.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use HTML entities:

  • instead of ' use &apos;
  • instead of " use &quot;

If you're creating the regexp using PHP, you can use htmlentities() to encode a string using HTML entities. By default, this will just encode double quotes, but you can use the ENT_QUOTES option to encode both types of quotes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...