I am trying to build a Nic validator without using Regular Expression(regex).
//Nic validation // Expected output format 12345-1234567-1
Here is my code sample. What I am unable to figure out is how do I validate numbers and hyphens only?
let nicVal= myForm.nic.value;
let hyph ='-';
if(nicVal.length===0){
console.log("Please enter the cnic");
}
else if(nicVal[5]===hyph && nicVal[5]===hyph )
{
console.log("Valid");
}
else{
console.log("invalid");
}
It would be much simpler using regular expressions, but as you ask for an alternative without a regex, try:
let button = document.querySelector('button') let input = document.querySelector('input') button.addEventListener('click', function() { let value = input.value let numbers = [Number(value.substr(0, 5)), Number(value.substr(6, 7)), Number(value.substr(14, 1))] numbers = numbers.map(value => {if(isNaN(value)) return 'NaN'; else return value}) let hifens = [value.indexOf('-'), value.lastIndexOf('-')] if(numbers.indexOf('NaN') == -1 && hifens[0] == 5 && hifens[1] == 13) { console.log('Valid.') } else { console.log('Invalid!') } })
<input type="text" placeholder="type..." maxlength="15" value="12345-1234567-1"> <button>Check</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.