How do I .addClass() when a regex condition is matched, using JQuery?
I have the following code, see below:
$(document).ready(function(){
var prefixNumber = $('.numeric').val();
if(prefixNumber.match(????){
prefixNumber.addClass('.field-error');
}
});
What I'm looking to happen is when the user types something in the input.numeric
field a开发者_如何学Gond it doesnt match one of these numbers, say...1, 3, 8 or 999 a class .field-error
is added to the input field which has a red background colour. Kind of trying to make a live error notification if that makes sense.
Any help would be greatly appreciated, Thanks
Use a change handler on your input:
$('.numeric').change(function () {
$(this).toggleClass('field-error', /[^0-9]/.test(this.value));
});
If you only have a couple of numbers, there is no need for regex (especially as they don't have a pattern). You can use an object instead:
var valid = {
1: true,
3: true,
8: true,
999: true
};
Then you have to decide when to evaluate the value. If it is while the user is typing, listen to the keyup
(or keydown
) event:
var timer = null;
function validate() {
var val = $('.numeric').val()
$('.numeric').toggleClass('field-error', val !=='' && !valid[+val]);
}
$('.numeric').keyup(function() {
clearTimeout(timer);
setTimeout(validate, 400); // time has to be adjusted...
});
DEMO
Try:
if (!prefixNumber.match(/^\d+$/)) {...}
It forces the prefixNumber to only consist of digits.
$(document).ready(function(){
var prefixNumber = $('.numeric');
if(!prefixNumber.val().match(/^(1|3|8)$/){
prefixNumber.addClass('field-error');
}
});
That would display an error if the input isn't 1, 3 or 8 :)
Moved your val()
method.
精彩评论