HTML5& quot; pattern& quot;的Javascript后备广告< input& gt;上的属性 [英] Javascript fallback for the HTML5 &quot;pattern&quot; attribute on &lt;input&gt;
问题描述
我正在使用HTML5模式"属性进行客户端验证(请不要告诉我有关服务器端验证的信息,我已经知道了).我想为使用不带模式"支持的浏览器的用户使用Javascript或jQuery后备.有什么好方法吗?
I'm using the HTML5 "pattern" attribute for client side validation (please don't tell me about server-side validation, I have that). I want to use a Javascript or jQuery fallback for users using browsers without "pattern" support. What's a good way to do that?
这是一个示例输入元素:
Here's an example input element:
<input type=tel name=contact[phone] id=phone required pattern=^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$>
推荐答案
在表单(或任何地方)的submit
事件上,使用其现有的pattern
属性对其进行验证.
On the submit
event of your form (or wherever), validate it using its existing pattern
property.
var input = document.getElementsByName('contact[phone]')[0],
isValid = input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0;
jsFiddle .
您将要首先检查浏览器的兼容性,以查看其是否支持pattern
属性.您可以使用 Modernizr .
You will want to check browser compatibility first to see if it supports the pattern
attribute. You can do that with Modernizr.
这篇关于HTML5& quot; pattern& quot;的Javascript后备广告< input& gt;上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!