Last active
June 17, 2024 16:19
-
-
Save freak4pc/6802be89d019bca57756a675d761c5a8 to your computer and use it in GitHub Desktop.
Israeli ID Validator (Javascript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isValidIsraeliID(id) { | |
var id = String(id).trim(); | |
if (id.length > 9 || id.length < 5 || isNaN(id)) return false; | |
// Pad string with zeros up to 9 digits | |
id = id.length < 9 ? ("00000000" + id).slice(-9) : id; | |
return Array | |
.from(id, Number) | |
.reduce((counter, digit, i) => { | |
const step = digit * ((i % 2) + 1); | |
return counter + (step > 9 ? step - 9 : step); | |
}) % 10 === 0; | |
} | |
// Usage | |
["1234567890","001200343", "231740705", "339677395"].map(function(e) { | |
console.log(e + " is " + (isValidIsraeliID(e) ? "a valid" : "an invalid") + " Israeli ID"); | |
}); | |
// Outputs: | |
// 1234567890 is an invalid Israeli ID | |
// 001200343 is an invalid Israeli ID | |
// 231740705 is a valid Israeli ID | |
// 339677395 is a valid Israeli ID |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
func isValidIsraeliID() -> Bool { | |
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines) | |
let isNumeric = rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil | |
guard 1...9 ~= trimmed.count, | |
isNumeric else { return false } | |
let neededZeros = 9 - trimmed.count | |
let tested = String(repeating: "0", count: neededZeros) + trimmed | |
return tested.enumerated() | |
.reduce(into: 0) { counter, args in | |
let (idx, char) = args | |
guard let digit = char.wholeNumberValue else { return } | |
let step = digit * ((idx % 2) + 1) | |
counter += step > 9 ? step - 9 : step | |
} % 10 == 0 | |
} | |
} |
hello, is there anyway to turn this into a regexp ?
thanks
@landesm Don't see how. Regex is for matching, not complex computation.
@freak4pc
Thank you for the swift version!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't need
var
here:var id = String(id).trim();
.