I need your advice (I'm a beginner in JS).This is my code:
function fn(pin) {
if (pin.length === 4 && !isNaN(pin) && pin % parseInt(pin) === 0 && Number(pin) > 0) {
return true;
}
return false
}
console.log(fn("123a.78")) // false
So i check the length, that it is a number, that it is integer and that it is bigger than 0. But how should i write the condition to eliminate strings of this type: "12.0" (because it also has length of 4 and is also integer)? If i try conditions with pin.parseFloat or parseInt, it will affect strings like this type "1234" as well. Or maybe i write them in the wrong way...
I would go with a regular expression to validate the input. The regular expression to validate 4 digits only would look like this: /^[0-9]{4}$/
Regular expressions have methods that allow them to test if variables are of their type. For instance:
const pin = '1234';
const pin2 = '12.4'
const regExp = /^[0-9]{4}$/
regExp.test(pin) //returns true
whereas:
regExp.test(pin2) //returns false
You can use this validation as the condition in your if/else conditions to execute the code you need.
freecode tutorial on Regular Expressions https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#es6
Regular expressions playground: https://regex101.com/