Simple Pin Validation
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
Solution 1:
functionvalidatePIN (pin) {
returntypeof pin === 'string' && // verify that the pin is a stringNumber.isInteger(+pin) && // make sure that the string is an integer when converted into a number
[4, 6].includes(pin.length) // only accepts 4 and 6 character pins
}
Solution 2:
functionvalidatePIN(pin) {
var isNumber = /^\d+$/.test(pin) && (pin.length == 4 || pin.length == 6)
return isNumber
}
validatePIN('0193')
//returns true
Solution 3:
You can use Array.prototype.every()
, Array.prototype.some()
, String.prototype.match()
<inputtype="text" /><button>validate pin</button><script>varvalidatePIN = (args) => {[...args] = args;
return args.every(v => v.match(/\d/)) &&
[4, 6].some(n => args.length === n)};
document.querySelector("button")
.addEventListener("click", (e) =>alert(validatePIN(e.target.previousElementSibling.value))
)
</script>
Solution 4:
function validatePIN (pin) {
//return true or falsereturn /^\d+$/.test(pin) && (pin.length === 4 || pin.length === 6)
}
Solution 5:
function validatePIN (pin) {
if (pin.length !== 4 && pin.length !== 6) {
returnfalse;
}
for (let i = 0; i < pin.length; i++) {
if (pin[i] > '9' || pin[i] < '0') {
returnfalse;
}
}
returntrue;
}
Post a Comment for "Simple Pin Validation"