HTML5文本字段的正则表达式模式 [英] Regex Patterns for HTML5 Text Field

查看:135
本文介绍了HTML5文本字段的正则表达式模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中为使用地址的html text field创建正则表达式模式.因此,我只希望用户输入[a-z,A-Z,0-9],而仅输入这些符号[,#-.],我还希望防止用户发送空字符串并且最大字符数小于100.

I would like to create a regex pattern in javascript for a html text field that takes an address. So I only want the user to enter [a-z,A-Z,0-9] and only these symbols [,#-.] I also want to prevent the user from sending an empty string and the maximum number of characters to be less than 100.

这是html <input>:

<input type="text" id="addy" maxlength="100"/>

我是javascript的新手,所以我不知道如何创建一个能够使正则表达式模式得到遵守的函数.

I'm new to javascript, so I do not know how to create a function that will enable the regex patterns to be adhered to.

谢谢

编辑

按照kolink的建议,我尝试了此操作:

Following the recommendation by kolink I tried this:

 <input type="text" style="width:285px" placeholder="Enter A Precise Address" name="address0" id="address"
     pattern="[ a-zA-Z0-9,#.-]+" maxlength="100" title="Standard address notation only"/>

现在这仅在未选择其他<select>的情况下有效.否则,它不会拾取pattern属性.但是,完全相同的代码可以在jsfiddle上正常工作: http://jsfiddle.net/peD3t/7/,但不在浏览器中.这是pastebin中的代码: http://pastebin.com/qQGJ4EK5

This now only works if the other <select> have not been selected. Otherwise it does not pick up the pattern attribute. However the exact same code works as expected on jsfiddle: http://jsfiddle.net/peD3t/7/ but not in the browser. This is the code in pastebin: http://pastebin.com/qQGJ4EK5

谢谢

推荐答案

HTML5为您提供了pattern属性,该属性允许您要求某种模式.在这种情况下,您需要pattern="[a-zA-Z0-9,#.-]+"

HTML5 gives you the pattern attribute, which allows you to require a certain pattern. In this case, you'd want pattern="[a-zA-Z0-9,#.-]+"

较旧的浏览器不支持此功能并不重要,因为您应该始终在服务器端进行验证.

It doesn't matter that older browser don't support this, because you should always validate on the server side.

这篇关于HTML5文本字段的正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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