How to create expression to allow only a few characters?

3

I am creating an input where an onKeyUp checks the entered characters, it should validate the following:

  • Maximum number of characters
  • The first digit should be just numbers [0-9]
  • The code is composed of alphanumeric digits and only the / (bar) and - (hyphen) characters, and they will not always have all of them.

Valid:

260509
8605/05
5ABC605/05
756574-7
88BS-AS0

Invalid:

A8605/05
B756574-7

Using the expression:

/^\d([\w\/-]*)/gm

I can match the values correctly, however I need to insert it into the function:

this.value=this.value.replace(/^\d([\w\/-]*)/gm,'')

But the function must have the operation reversed, when it does not match, replace with "".

    
asked by anonymous 23.10.2015 / 19:58

1 answer

3

The problem of validating as the user types is that it is not necessary that the entire field is valid but that a prefix is the same (otherwise the user would never be able to finish typing, unless you paste the entire value with Ctrl + V), and only at the end a complete field validation can be done. In your case however it is easy, since only a single digit is mandatory and the others are optional:

document.querySelector("input").onkeyup = function(e) {
    this.value = this.value.replace(/^\D.*|[^\w\/-]/gm,'');
}
<input>

This code deletes the entire field if the first digit is not a number, or deletes each specific character that is not in the given set (i.e. its allowed character set, denied). If the user pasts the field from somewhere else, only the valid characters will remain.

The main disadvantage of this method is that it does not preserve caret . It would be highly desirable that the user could go back with the arrows and correct an incorrect passage, but that would complicate matters a little.

Note: This answer assumes that only the incorrect excerpt should be deleted in the override, not the entire code - otherwise, if the user was typing and accidentally entered an invalid character, everything disappeared, I think he was not going to be very pleased ...

    
23.10.2015 / 20:48