I have a input that has to format what's the user typing(actually it is info from his bank account). But the numbers have to be formatted in a certain way:
examples:
Actually I'm using a normalizer that replaces the string.
This is what I'm using but I cant format it correctly.
export const normalizeBankAccount = value => {
if (!value) {
return value
}
if(value.length <= 16 && (!value.match(/[^\d|X]/g) || !value.match(/[^\d|-]/g) || !value.match(/[^\d|x]/g))) {
if(value.length <= 5){
return value.replace(/[^\d]/g, '')
} else if(value.length >= 6) {
const len = value.length;
const aux=value;
const initial = value.substring(0,value.length-1).replace('-', '');
console.log("len: " +len, "\naux: " +aux,"\ninitial: "+ initial)
return value.replace(new RegExp("\\d{"+ len +"}") , initial+ '-').replace(/[X]/g, '-X').replace(/[x]/g, '-x')
}
}
}
When I use this method, the string is formatted like this:
You could look for a given length, followed by a single character and add a minus sign.
const
normalize = string => string.replace(/^\d{5,14}(?=[0-9x]$)/i, '$&-');
console.log(['12345', '123451', '1234561', '12345671', '12345x', '123456789x', '123456789X', '123456789012345'].map(normalize));
Example with input.
function update(element) {
element.value = element.value
.replace(/[^0-9x]/gi, '')
.replace(/x(?=.)/gi, '')
.replace(/^\d{5,14}(?=[0-9x]$)/i, '$&-');
}
<input type="text" onkeyup="update(this)" id="x">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With