Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  84] [ 4]  / answers: 1 / hits: 26939  / 6 Years ago, thu, march 8, 2018, 12:00:00

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 :)


More From » javascript

 Answers
35

/[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

[#54985] Monday, March 5, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shaynelandenb

Total Points: 293
Total Questions: 97
Total Answers: 94

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;