I want to validate in JavaScript that the username or password only accepts exactly 3 numbers with a regular expression.
I have the following, the problem is that when 1234
I enter it accepts it as correct, I need to validate this to be able to carry out the rest of my page.
function validar() {
usuario = document.getElementById('usuario').value;
patron = /\d{3}/;
if(patron.test(usuario)){
alert("correcto")
}else{
alert("ERROR")
}
Let's go by parts, from simpler to more complicated, and simplifying everything in the end.
1. Only 3 digits
If it was just to see if it has 3 digits, why use regex? It's a number between 100 and 999, right?
2. 3 digits at the end
But if the user is a name ending in 3 digits, then we have to guarantee that the regex matches from the beginning (
^
) to the end of the text ($
).Recall that a regular expression matches any part of the text (the first it finds). That's why your code failed, because it matched the first 3 digits within the 4 that the text had.
So, we force to match the starting position, any number of non-digit characters, all 3 digits, and the ending position of the text.
\D
matches 1 character, any character that is not a digit (it is the same as[^0-9]
; and*
it repeats between 0 and infinite times.3. Regex for exactly 3 digits in any position
Now, if they can be anywhere, you have to allow
\D*
in between each other, which would be something like/^\D*\d\D*\d\D*\d\D*$/
.But it can be made simpler, by using a group
(?:
...)
and repeating to that group:4. Remove everything that is not a digit
But perhaps, it will be much easier for you to eliminate everything, leaving only the digits and using the same as in the first point:
The problem with your expression is that if you write a text that has 3 numbers in a row, it will return true because that is what your expression means.
You have to indicate that from the beginning to the end of the string, it only contains 3 numbers using
^
at the beginning and$
at the end:^
means search at the beginning of the string and$
at the end.