<input id="phone" name="phone" placeholder="(XXX)XXX-XXXX" type="tel"
pattern="^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$" required="true"/>
How can I validate if that pattern is used in JavaScript for browsers that don't support the pattern attribute?
Thank you for your input -- I've tried doing several options below, but I can't seem to get anything to trace out as "true" -- the RegExp works in the HTML pattern field for FireFox and Chrome. But it's always returning false when I'm trying to utilize it with javaScript?
There are a number of polyfills that will enable this in older browsers:
I'd recommend polyfilling -- this doesn't change the behavior for modern browsers but emulates it in old ones. (An aside: the Modernizr polyfills list is fantastic.)
You could also write it yourself; some other answers show how that's done.
Create an onchange
event that reads the pattern
attribute and runs it against the value
.
// Only bind event if we need to
if(!('pattern' in document.createElement('input'))){
// Bind the event
document.getElementById('phone').addEventListener('change', function(){
// Get the regex and value then test it
var regex = new RegExp(this.pattern),
val = this.value,
valid = regex.test(val);
// Is it valid?
if(!valid){
// Do something when it's not
}
});
}
You should validate when submitting the form, or losing focus from the input.
If you use jQuery, this will work for all elements with pattern
attribute:
$('[pattern]').each(function() {
if (!$(this).val().match($(this).attr('pattern')))
alert('Bad value');
});
If not, you can do something for this (similar):
var inputs = getElementsByName('input');
for (var index in inputs) {
var input = inputs[index];
var pattern = input.getAttribute('pattern');
if (pattern != '' && pattern != null) {
if (!input.value.match(pattern))
alert('Bad value');
}
}
These will loop through the attributes that have a pattern to identify against, check them, and alert the user if there's a problem. Of course, you can change the alert to whatever way you would like to handle it (for example, return false to cancel the form submission).
I haven't tested this code, but that's the gist of it.
You can use polyfill or add onchange
event to your input.
document.getElementById('phone').addEventListener('change', function(){\
// returns true if input matches regexp, otherwise it returns false
var isValid = RegExp(this.pattern).test(this.value);
});
var regex = /^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$/;
if(phone.value.match(regex)){
console.log('true');
}else{
console.log('false');
}
I just ended up using this... It worked. @_@
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.