Bạn có thể kiểm tra mã PIN dựa trên độ dài và kiểu dữ liệu (phải là chuỗi, không chứa dấu chấm, chỉ chứa số, độ dài 2 hoặc 4).
Ví dụ
Mã nguồn:
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")
Chạy với lệnh:
node fileName.js
Tên file: demo254.js.
Kết quả
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