用于HTML5“模式”的Javascript回退属性on<输入> [英] Javascript fallback for the HTML5 "pattern" attribute on <input>
问题描述
我使用HTML5模式属性进行客户端验证(请不要告诉我有关服务器端验证的信息,我有这个)。我想为使用浏览器但没有模式支持的用户使用Javascript或jQuery后备。
以下是一个输入元素示例:
< input type = tel name = contact [phone] id = phone required pattern = ^(?:( ?: \ +?1 \s *(?:[.-] \s *)? )(?:\(\s *([2-9] 1 [02-9] | [2-9] [2月8日] 1 | [2-9] [2月8日] [02- 9])\s * \)|([2-9] 1 [02-9] | [2-9] [2月8日] 1 | [2-9] [2月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\ |扩展)\s *(\d +))$>?
code>您的表单(或任何地方)的事件,使用其现有的模式
属性进行验证。
var input = document.getElementsByName('contact [phone]')[0],
isValid = input.value.search(new RegExp(input.getAttribute('pattern') ))> = 0;
jsFiddle 。
您需要首先检查浏览器兼容性,看它是否支持模式
属性。你可以用 Modernizr 来做到这一点。
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+))?$>
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;
You will want to check browser compatibility first to see if it supports the pattern
attribute. You can do that with Modernizr.
这篇关于用于HTML5“模式”的Javascript回退属性on<输入>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!