Computer >> Computer tutorials >  >> Programming >> Javascript

Set PIN validation with JavaScript?


You can validate pin on the basis of length and type of pin must be string etc.

Example

Following is the code −

function simpleValidationForPin(pinValues) {
   if (!(typeof pinValues === "string" && !~pinValues.indexOf('.') && !isNaN(Number(pinValues)) && (pinValues.length === 2 || pinValues.length === 4))) {
      return false;
   } else {
      return true;
   }
}
if (simpleValidationForPin("0000.00") == true)
   console.log("This is a valid pin")
else
   console.log("This is not a valid pin")
if (simpleValidationForPin(66) == true)
   console.log("This is a valid pin")
else
   console.log("This is not valid pin")
if (simpleValidationForPin("4444") == true)
   console.log("This is a valid pin")
else
   console.log("This is not a valid pin")
if (simpleValidationForPin("66") == true)
   console.log("This is a valid pin")
else
   console.log("This is not valid pin")
if (simpleValidationForPin("666") == true)
   console.log("This is a valid pin")
else
   console.log("This is not a valid pin")

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo254.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo254.js
This is not a valid pin
This is not a valid pin
This is a valid pin
This is a valid pin
This is not a valid pin