6
I have a field that accepts at least 12 alphanumeric characters, including 9 numeric characters. But there is a catch, that accepts white space whatever the position.
function validaCampo(sCampo) {
var filter = /^(?=.*?[a-z])(?=(?:.*?\d){9})[a-z\d]{12,}$/i;
if (filter.test(sCampo)) {
return true;
} else {
return false;
}
}
I think putting the
\
at the end within the[]
should work.var filter = /^(?=.*?[a-z])(?=(?:.*?\d){9})[a-z\d\ ]{12,}$/i;
– Icaro Martins
A hint of improvement:
^(?=[^a-z]*[a-z])(?=(?:\D*\d){9})[a-z\d ]{12,}$
- mainly use\D*
(zero or more non-numeric characters) is more efficient than.*?
, since.*?
generates more possibilities to be tested and when the string is invalid regex takes longer to realize it. Compare, that one takes almost 2000 steps to fail, already that one takes only 52 steps. For small strings it doesn’t make much difference, but if you have a lot of tests and large strings, it might help...– hkotsubo
@hkotsubo Understood. I will. Thank you!
– Fabiano Monteiro