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).
Wouldn’t it be the case just to escape them? It would look something like this:
(/[^\d\+\(\)]/g, '')
– Felipe Avelar
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/)– hkotsubo
@Felipeavelar In square brackets these characters do not need to be escaped: https://jsfiddle.net/8o5zhkL7/
– hkotsubo
@hkotsubo I will check. Thank you very much.
– Levi