Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript fallback for the HTML5 "pattern" attribute on <input>

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+))?$>
like image 304
Leo Jiang Avatar asked Nov 28 '11 03:11

Leo Jiang


1 Answers

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.

like image 126
alex Avatar answered Oct 13 '22 00:10

alex