Regex because only true if put above 5 numbers?

Asked

Viewed 89 times

2

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>

I wonder why this code shows only true even above 5 numbers typed?

  • 1

    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.

  • 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

2 answers

5

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>

  • Actually, if the string is abc1234xyz, also gives match, because when regex doesn’t have markers like ^ and $, it looks for 4 digits at any point in the string

  • 1

    @hkotsubo That was my intention, but I ended up not foreseeing this situation haha was worth

1

The problem was only in your regex, the correct is:

var reg = /^[0-9]{0,4}$/;

Totaling length a maximum of 4 digits, with the marker also required ^ to check inside the numbers and not the String.

function checkreg() {
  var reg = /^[0-9]{0,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>

Browser other questions tagged

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