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
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.
My best guess would be first having a function that uses jQuery to find the browser and version, and match that up to if it supports pattern or not, and then do something like
$("#element").onChange(function()
{
if(doesNotSupportPattern())
{
var pattern = $(this).prop('pattern');
if(!$(this).val().match(pattern)))
{
//Code to make form invalid
}
}
});
Or something of the like
Change of plan, this isn't the way to go
$("#form").submit(function()
{
var valid = true;
$(this).find('input').each(function()
{
if(!$(this).prop('pattern'))
continue;
if(!$(this).val().match($(this).prop('pattern')))
valid = false;
});
if(!valid)
{
//invalidate form
}
});
Would be better off. This way it'll trigger for each element, and it's more compact, and if pattern is enabled, it'll not interfere anyway, as it should only submit if it all matches, and if it doesn't, the form is invalidated anyway
You can use Modernizr to check to see what's supported by the user's browser.
Detecting HTML5 with Modernizr
Modernizer lets you do stuff like this:
if (Modernizr.canvas) {
// let's draw some shapes!
} else {
// no native canvas support available :(
}