HTML 模式 - 正则表达式不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16542665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML Pattern - regex not working
提问by John Smith
I'm trying the pattern attribute for the first time, and I can't get it to work (my browser does support it, though).
我是第一次尝试模式属性,但我无法让它工作(不过我的浏览器确实支持它)。
Right now I have:
现在我有:
input type="text" pattern="[a-zA-Z0-9]{6}" name="formName"
The first problem is that is doesn't notify me if it's blank; the second problem is that if I do type in something, it won't accept it. I want it to accept alphanumeric characters and be exactly 6 characters is length. I tried it with forward slashes and a few other variations.
第一个问题是如果它是空白的,它不会通知我;第二个问题是,如果我输入了一些东西,它不会接受它。我希望它接受字母数字字符,并且长度正好是 6 个字符。我尝试使用正斜杠和其他一些变体。
回答by gkalpak
As Duikboot already pointed out, the right way to do it is:
正如 Duikboot 已经指出的那样,正确的做法是:
<input type="text" name="formField" pattern="[a-zA-Z0-9]{6}" required>
The required
attribute causes the validation to fail, when the field is empty.
The pattern
attribute defines the regex to test against, when the field is not empty.
(Your initial pattern seems to work fine.)
required
当字段为空时,该属性会导致验证失败。当字段不为空时,
该pattern
属性定义要测试的正则表达式。
(您的初始模式似乎工作正常。)
More info can be found here.
This is simple enough so as not to require a demo, but nonetheless you can find one here.
回答by barbuslex
Works for me here : http://jsfiddle.net/barbuslex/nR6yg/
在这里为我工作:http: //jsfiddle.net/barbuslex/nR6yg/
<form>
<input type="text" pattern="[a-zA-Z0-9]{6}" name="formName" />
<input type="submit" value="OK" />
</form>
I use Google Chrome
我使用谷歌浏览器
回答by Golda
Try this code its working perfectly
试试这个代码它的工作完美
<html>
<body>
<form action="demo_form.asp">
Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
<input type="submit">
</form>
</body>
</html>
Enter invalid country code and click submit button. Then You can get a message (title="Three letter country code")
输入无效的国家代码并单击提交按钮。然后你可以得到一条消息(标题=“三个字母的国家代码”)
回答by c4po
You simply need to add the required attribute to your tag, which will notify the user if they attempt to send the form with that very field blank.
您只需将 required 属性添加到您的标签,如果用户尝试发送该字段为空白的表单,它将通知用户。
<input type="text" pattern="[a-zA-z0-9]{6}" name="formName" required>