Allow certain characters in an input text

Asked

Viewed 271 times

0

I have the following expression::

(/[^\d]/g, '')

I’m using this expression in a Javascript function so that a input type="text" accept only numbers. The problem is that I now need this function to also allow characters ()+.

I’ve done some research but I didn’t find anything very didactic, since I started messing with regular expressions recently.

How could you enable these characters through regular expressions?

  • 2

    Wouldn’t it be the case just to escape them? It would look something like this: (/[^\d\+\(\)]/g, '')

  • 1

    How are you using regex? Why [^\d] actually takes anything other than number (and already allows characters (, ) and +, see: https://regex101.com/r/AUKban/1/)

  • 2

    @Felipeavelar In square brackets these characters do not need to be escaped: https://jsfiddle.net/8o5zhkL7/

  • @hkotsubo I will check. Thank you very much.

2 answers

2


I think that solves: [^\d()+]

const f = (ev) => {
if(ev.key.match(/[^\d()+]/)) {
ev.preventDefault();
}
}
<input type="text" onkeypress="f(event)" />

2

One solution is to use the attribute pattern of input:

const campo = document.querySelector('#campo');

campo.addEventListener('input', () => {
  campo.setCustomValidity('');
  campo.checkValidity();
});

campo.addEventListener('invalid', () => {
    campo.setCustomValidity('O campo só pode ter números ou os caracteres ()+');
});
/* deixar borda vermelha enquanto o campo for inválido */
input:invalid {
  border: red 1px solid;
}
<form>
  <input id="campo" type="text" pattern="^[\d()+]+$" required />
  <input type="submit" value="ok">
</form>

The pattern receives a regular expression saying exactly what he may have. In this case, I used ^[\d()+]+$.

The markers ^ and $ are respectively the beginning and end of the string. Thus, I guarantee that the field will only have what I determine.

Next I have the character class [\d()+] that takes any character that is \d (one shortcut which means "digit of 0 to 9"), or a (, or ), or +.

Soon after we have the quantifier +, meaning "one or more occurrences". That is, the field may have one or more characters, provided that they correspond to [\d()+]. But if you want, you can switch to more specific quantities:

  • [\d()+]{5,20}: not less than 5 and not more than 20 characters
  • [\d()+]{5,}: at least 5 characters, with no maximum limit
  • [\d()+]{5}: exactly 5 characters

Adjust the values according to what you need.


The difference of this solution to the another answer is that it does not prevent the user from entering invalid characters. It only prevents the form from being submitted (and shows a message if it tries to submit with invalid data - this message can be exchanged with setCustomValidity, as shown above).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.