jquery validation allow to enter code between user1 to user100

Viewed 61

This is my the example where user can enter the code between 1 to 100 only otherwise return false.

var regexCode = /var regexEmail = /^0*(?:[1-9][0-9]?|100)$/;

 
 $(document).on('change','#code',function(){
    if (!regexCode.test($("input#code").val())) {
      alert("Please enter valid code");
      $("input#code").focus();
      return false;
    }
});
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input name="code" id="code" placeholder="code" required>

Now it accepting digits between 1 to 100 but I need it to accept the code e.g between

user1 to user100 only otherwise return false.

3 Answers

lot of solution with : regexp

var regexCode = /^user(?:[1-9][0-9]{0,1}|100)$/;

 
 $(document).on('change','#code',function(){
    var result = $("input#code").val();
    if (!regexCode.test($("input#code").val())) {
      alert("Please enter valid code");
      $("input#code").focus();
      return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input name="code" id="code" placeholder="code" required>

You can use this regex /^[1-9][0-9]$|^100$/ explain:

^[1-9][0-9]? should mens starts digit with two or one (first doesn't accept 0 )range number - 0 --> 99

| or operator

^100$ start and end only with the number 100

also think to remove last added number from value using :

value = value.substring(0, value.length - 1);
$(this).val(value);

Belw in snippt I've used on Input event to check for every keyboard input

var regexCode = /^[1-9][0-9]?$|^100$/;

 
 $(document).on('input','#code',function(e){
    let value = $(this).val();
    
    
    if (!regexCode.test($(this).val())) {
      alert("Please enter valid code");
      value = value.substring(0, value.length - 1);
      $(this).val(value)
      $("input#code").focus();
      return false;
    } else {
      $("#output").html("user"+value)
    }
    
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input name="code" id="code" placeholder="code" required> rang betwwen 0-100
<br><br>
user id = <span id="output"></span>

You can use HTML Pattern for this purpose.

<input type="text" name="code" id="code" placeholder="code" pattern="user[0-9]{1,2}" required />
Related