用于HTML5“模式”的Javascript回退属性on<输入> [英] Javascript fallback for the HTML5 "pattern" attribute on <input>

查看:83
本文介绍了用于HTML5“模式”的Javascript回退属性on<输入>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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;

jsFiddle.

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&lt;输入&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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