I'm trying to solve this task:
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false.
eg:
validatePIN("1234") === true validatePIN("12345") === false validatePIN("a234") === false
And this is my code:
function validatePIN (pin) {
if(pin.length === 4 || pin.length === 6 ) {
if( /[0-9]/.test(pin)) {
return true;
}else {return false;}
}else {
return false;
}
}
It shows that --- Wrong output for 'a234' - Expected: false, instead got: true ---Why? This /[0-9]/ shows only numbers?
Thank you in advance :)
/[0-9]/ will match any number in the string, so it matches the "2" in "a234". You need to make it match only numbers, from beginning to end: /^[0-9]+$/ or /^\d+$/
Additionally, you can just use the regular expression /^(\d{4}|\d{6})$/ to match all strings containing 4 or 6 numbers.
/^(\d{4}|\d{6})$/.test("1234"); // true
/^(\d{4}|\d{6})$/.test("12345"); // false
/^(\d{4}|\d{6})$/.test("123456"); // true
/^(\d{4}|\d{6})$/.test("a234"); // false
As you can see in this regex example /[0-9]/ will match any string that has at least 1 number anywhere in it.
To fix this you can use quantifiers to match exactly either
[0-9]{4}[0-9]{6}Additionally, we want these regexes to actually match the entire string, using ^ at the start, and $ at the end of the regex. This will make sure nothing exists next to a matched pin code.
If we combine the 2 cases above in a capture group, and add the start- and end-delimiters, we end up with this regex:
/^([0-9]{4}|[0-9]{6})$/
Note: the [0-9] character set has a nice shorthand: \d, so the regex could be further simplified to:
/^(\d{4}|\d{6})$/
This single regex performs all the validation you need, so in your code validatePIN could be simplified as follows:
function validatePIN (pin) {
return /^(\d{4}|\d{6})$/.test(pin);
}
console.log(validatePIN('1234')); // > true
console.log(validatePIN('123456')); // > true
console.log(validatePIN('123')); // > false
console.log(validatePIN('12345')); // > false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With