She does not return true
only when you put in 5 digits or more, that’s when you put in 4 or more, because what your regular expression defines is "see if there are 4 digits between 0 and 9". Any composite value with 4 or more digits will have 4 digits. In fact, any value that has 4 consecutive digits will make the return true, such as "abc1234xyz"
, as recalled by hkotsubo.
If the idea is that it is valid 4-digit only, just limit regex to the characters ^
and $
which, respectively, indicate the beginning and end of the value, thus containing only what you want.
function checkreg() {
var reg = /^[0-9]{4}$/;
var verificaInput = document.querySelector("#agencia").value;
console.log(reg.test(verificaInput))
}
<label>
<input type="number" name="agencia" id="agencia"/>
<input type="button" value="click to check" onclick="checkreg(this.id)"/>
</label>
Because your regex is limiting it to be a number of only
{4}
digits... as you did not set the beginning and the end, it will validate this to 4 numbers only.– Ivan Ferrer
Complementing the answers below, you can also use
\d
in place of[0-9]
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-Digit– hkotsubo