Issue
I want to insert hyphen to validate a ID number. For example, my card number format would be something like 123 - 2342 - 1232321 - 1 (over all only 15 numbers) user should not be allowed to enter more than 15 digits. I need to add hyphen once the above set of digits is entered by the user with a space before and after each digit. First hyphen should be added after 3 digits , secone hyphen after entering 4 digits, third hyphen to be added after entering 7 digits. How can I validate this?
<div>
<input type="text" id="tbNum" ng-keypress="addHyphen(this)"
placeholder="Type some values here" />
</div>
$scope.addHyphen = function(element) {
let ele = document.getElementById(element.id); // ele doesnt have id value
ele = ele.value.split('-').join('');
let finalVal = ele.match(/.{1,3}/g).join('-');
document.getElementById(element.id).value = finalVal;
};
I tried to implement the above way , but element.id doesnt capture the id value of the input field.
Solution
function addHyphen(elem) {
if (elem.value.length <= 17) {
if (elem.value.length === 3) {
elem.value = `${elem.value}-`;
}
if (elem.value.length === 8) {
elem.value = `${elem.value}-`;
}
if (elem.value.length === 16) {
elem.value = `${elem.value}-`;
}
} else {
elem.value = elem.value.slice(0, -1)
}
};
<div>
<input type="text" id="tbNum" onkeypress="addHyphen(this)" placeholder="Type some values here" />
</div>
You can use regex
for that, try below
Try something like below
$scope.addHyphen = function(element) {
if (elem.value.length <= 17) {
if (elem.value.length === 3) {
elem.value = `${elem.value}-`;
}
if (elem.value.length === 8) {
elem.value = `${elem.value}-`;
}
if (elem.value.length === 16) {
elem.value = `${elem.value}-`;
}
} else {
elem.value = elem.value.slice(0, -1)
}
};
PS: below regex can also help
let num = "123234212323211";
console.log(num.replace(/(\d{3})(\d{4})(\d{7})(\d{1})/, "$1-$2-$3-$4"));
Hope this helps
Answered By - Anand G
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.