javascript - Send pattern to a function -


i have personal function take id , pattern check 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 if condition return null (!input.match(pattern)). 2 console log return number write in input, , pattern correctly, why if false ?

when pass "/0[1-7,9]\d{8}/" string#match(), single \ before d removed unknown escape sequence , / around pattern treated literal / symbols in pattern. thus, no matches. also, , in character class considered literal comma, sure want remove pattern. besides, first pattern lacks ^ @ start , $ anchor @ end if plan match entire string. either pass "^0[1-79]\\d{8}$" or - preferred - use regex literal /^0[1-7,9]\d{8}$/ (no double quotes around pattern).

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

also, advisable replace if (!input.match(pattern)) if (!pattern.test(input)) regex.test(str) returns true or false while str.match(regex) either return null or array of match data.

so, 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}$/); }) 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - IE9 error '$'is not defined -