Buck Buck - 1 month ago 22
Javascript Question

Send pattern to a function

I have a personal function who take an id and a pattern for check some input.



var id, schema;
function checkField(id, schema){
var input = id.val();
var pattern = schema;

if (!input.match(pattern)){
console.log('Input = '+input);
console.log('Pattern = '+pattern);
id.removeClass().addClass("error");
$(".oke").css({display: 'none'});
}else{
console.log('Classe = ok');
id.removeClass().addClass("ok");
$(".nope").css({display: 'none'});
}
}

// Vérification téléphone
$("#tel").focusout(function(){
checkField($(this), "/0[1-7,9]\d{8}/");
});

// Vérification code postale
$("#cp").focusout(function(){
checkField($(this), "/^((0[1-9])|([1-8][0-9])|(9[0-8])|(2A)|(2B))[0-9]{3}$/");
});





But the if condition always return
null
(
!input.match(pattern)
).
The two console log return the number write in input, and the pattern correctly, why the if is always false ?

Answer

When you pass "/0[1-7,9]\d{8}/" to the String#match(), the single \ before d is removed as it is an unknown escape sequence and the / around the pattern are treated as literal / symbols in the pattern. Thus, you get no matches. Also, the , in the character class is also considered a literal comma, I am sure you want to remove it from the pattern. Besides, the first pattern lacks ^ at the start and $ anchor at the end if you plan to match the entire string. Either pass "^0[1-79]\\d{8}$" or - preferred - use a regex literal /^0[1-7,9]\d{8}$/ (no double quotes around the pattern).

The second pattern can be shortened as /^(0[1-9]|[1-8]\d|9[0-8]|2[AB])\d{3}$/ - again, note the absence of the double quotes around the regex literal notation.

Also, it is advisable to replace if (!input.match(pattern)) with if (!pattern.test(input)) as regex.test(str) returns true or false while str.match(regex) will either return null or an array of match data.

So, what you can use is

if (!pattern.test(input)){
...

$("#tel").focusout(function(){
    checkField($(this), /^0[1-79]\d{8}$/);
});

$("#cp").focusout(function(){
    checkField($(this), /^(0[1-9]|[1-8]\d|9[0-8]|2[AB])\d{3}$/);
})