HTML5使用包含引号的模式验证文本输入 [英] HTML5 Validate Text input using pattern containing quote

查看:97
本文介绍了HTML5使用包含引号的模式验证文本输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是帮助我构建我的正则表达式"问题之一.我有一个HTML表单输入字段,用户可以在其中输入各种格式的地理位置数据.以下正则表达式可以在 regexr.com 以及我的应用程序中正常运行.但是,我想使用HTML5的"pattern"参数在提交之前另外验证用户的输入.

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的addslashes()函数转义了太多字符.
  • 我用一个反斜杠转义了报价

那并没有改变任何东西.我在Chrome上进行了测试,该Chrome可以与简单的正则表达式配合使用.上面的那个显然太复杂了.

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.

我知道上面的正则表达式对于匹配坐标并不理想,但是,这里不做讨论.我只是想知道如何正确地转义HTML5中的模式,因为Chrome对该正则表达式不做任何事情.

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.

推荐答案

使用HTML实体:

  • 代替'使用&apos;
  • 代替"使用&quot;
  • instead of ' use &apos;
  • instead of " use &quot;

如果使用PHP创建正则表达式,则可以使用htmlentities()使用HTML实体对字符串进行编码.默认情况下,这只会对双引号进行编码,但是您可以使用ENT_QUOTES选项对两种类型的引号进行编码.

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.

这篇关于HTML5使用包含引号的模式验证文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆