Reputation: 3374
I have a text input with a custom oninvalid message:
<input id="foo" type="text" maxlength="16" required pattern="[a-zA-Z0-9]+"
oninvalid="this.setCustomValidity('Please enter letters and /
or numbers only.')" onBlur="chk()" autofocus>
In the onBlur event I want to run some code, but only if the text entered passed the pattern validation specified. Something like:
function chk() {
if (document.getElementById("foo").isvalid?()) {
bar();
}
}
Alternatively:
function chk() {
if ($("#foo").isvalid?()) {
bar();
}
}
Update
I found the following solution, but it does repeat the code of the pattern validation:
function chk() {
var exp = /^[a-zA-Z0-9]+$/;
if (exp.test($("#foo").val())) {
bar();
}
}
Upvotes: 2
Views: 2746
Reputation: 7273
You can grab the pattern from your input but we need to modify it slightly. As MDN explains: "the pattern pattern must match the entire value, not just some subset." This basically boils down to the browser implicitly prepending a ^
and appending a $
to the pattern value. So, for our case, when we grab that string pattern value from our input, we also need to do the same to match the browser's functionality:
function chk() {
var pattern = $("#foo").attr('pattern');
var exp = new RegExp('^' + pattern + '$');
if (exp.test($("#foo").val())) {
bar();
}
}
Upvotes: 1
Reputation: 2069
You don't need to recheck if the text matches the regular expression manually. You can just check the ValidityState.
function chk() {
if ($("#foo").validity.valid) {
bar();
}
}
Upvotes: 4
Reputation: 1790
first of all you want to create a regex with the pattern attribute you set in your input :
function chk() {
var pattern = this.getAttribute('pattern');
var regex = new RegExp(pattern);
// ...
}
and then verify if the input value match the regex :
function chk() {
var pattern = this.getAttribute('pattern');
var regex = new RegExp(pattern);
// regex matching
if (regex.test(this.value)) {
bar();
}
}
see this fiddle: https://jsfiddle.net/t6wLeqq0/1/
Upvotes: 1
Reputation: 2257
you can check onChange event and call that method everytime an input is changed
Upvotes: 1