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:
- the first 5 digits must be numbers.
- if the user type more than 5 numbers, the last number must have a '-' before it
- after the 5 digit, the user can type 'x' or 'X'
- the number can have minimun of 5 digits, and maximum of 15
examples:
- 12345
- 12345-1
- 123456-1
- 1234567-1
- 12345-x
- 123456789-x
- 123456789-X
- 12345678901234-5
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:
- 12345-6789123