Gulshan Prajapati
Gulshan Prajapati

Reputation: 393

how to check a string start with one alphabet then 4 digits number

how to check a string start with one alphabet then 4 digits number

i need to test a string by javascript regex . My string must starts with 'P' then 4 digit number must be. total length of sting should be 5(p + 4 digit number)

example : P1234 or p5263

i have tested with :

$(function(){
    
    $('.p-input').keyup(function(e){
      var entered_value = $(this).val();
      var regexPattern = /^[pP]+[0-9]{4}$/;         
                 
      if(regexPattern.test(entered_value)) {
          $(this).css('background-color', 'white');
          $('.err-msg').html('');
      } else {
          $(this).css('background-color', 'red');
          $('.err-msg').html('Enter a valid value');
      }
    });
    
});
.err-msg { font-size:small; font-style:italic; color:red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="" class="p-input" />
<span class="err-msg"></span>

but in above code it working with 'pp1236' , 'ppp1236'

in my code cant fix p occurrences.

Upvotes: 0

Views: 315

Answers (1)

DavidVollmers
DavidVollmers

Reputation: 695

You have to remove the +. It is a one or unlimited time quantifier, so in your example "p" or "P" has to occur one or more times.

Without the quantifier it means "p" or "P" has to occur only one time.

So this is the right RegExp: /^[pP][0-9]{4}$/

The site regex101.com is perfect for testing regular expressions in php, javascript and python :)

EDIT: In the comments of your question people recommend to use the {1} quantifier. This quantifier is "meaningless" because it is the default.

Upvotes: 4

Related Questions