3

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

1 Answer 1

3

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">

Sign up to request clarification or add additional context in comments.

10 Comments

It actually don't work because the numbers must be formatted as the user keeps typing
you need to clean the string from all minus signs and apply the normalization.
Almost working, I removed the minus sign as you said like this: ` string.replace('-', '').replace(/^\d{5,14}(?=[0-9x]$)/i, '$&-') ` But I cant type x or X
the replace with a string, instead of a regular expression replace only the first occurence of the find. the version with a regex and a global flag searches for all occurences.
you could remove unwanted characters. maybe you need another check for shorter items with 'x'.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.