dmikester1 – 19-23 Jul 19

anyone have any experience with masking inputs? I just want a very simple mask that looks like this 999-9999. I would like to avoid using a plugin for this simple use case.
D
dmikester1274d ago
I figured out a way that serves my purposes. Not sure if it is the best way or not, but it works. This is a React app, by the way.
const setTheItemID = (e) => {
let val = e.target.value.replace('-', '');
console.log(val);
if (val.length < 8) {
const re = /^[0-9\b]+$/;
if (val === '' || re.test(val)) {
if (val.length > 3) {
val = val.slice(0, 3) + '-' + val.slice(3);
}
setItemID(val);
}
} else {
val = val.slice(0, 3) + '-' + val.slice(3, 10);
setItemID(val);
}
};
const setTheItemID = (e) => {
let val = e.target.value.replace('-', '');
console.log(val);
if (val.length < 8) {
const re = /^[0-9\b]+$/;
if (val === '' || re.test(val)) {
if (val.length > 3) {
val = val.slice(0, 3) + '-' + val.slice(3);
}
setItemID(val);
}
} else {
val = val.slice(0, 3) + '-' + val.slice(3, 10);
setItemID(val);
}
};
Even better!
const setTheItemID = (e) => {
let originalVal = e.target.value;
let val = originalVal.replace('-', '');
console.log(val);
if (val.length < 8) {
const re = /^[0-9\b]+$/;
if (val === '' || re.test(val)) {
if (val.length > 3) {
val = val.slice(0, 3) + '-' + val.slice(3);
}
if (originalVal.length === 4 && originalVal[3] === '-') {
val = val + '-';
}
setItemID(val);
}
} else {
val = val.slice(0, 3) + '-' + val.slice(3, 9);
setItemID(val);
}
};
const setTheItemID = (e) => {
let originalVal = e.target.value;
let val = originalVal.replace('-', '');
console.log(val);
if (val.length < 8) {
const re = /^[0-9\b]+$/;
if (val === '' || re.test(val)) {
if (val.length > 3) {
val = val.slice(0, 3) + '-' + val.slice(3);
}
if (originalVal.length === 4 && originalVal[3] === '-') {
val = val + '-';
}
setItemID(val);
}
} else {
val = val.slice(0, 3) + '-' + val.slice(3, 9);
setItemID(val);
}
};
UU
Unknown User272d ago