javascript regexp validation to match specific pattern to accept from textbox

Viewed 38

I have one form with textbox and user needs to insert width X height format value so I need to validate whether it is in correct format or not using JavaScript regexp validations.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<input type="text" name="txt" class="txt_val" value=""/>
<input type="submit" class="clk" value="submit"/>

<script>
  $(".clk").click(function(){
    var number=$(".txt_val").val();
    var compare=/[0-9]{2}^[a-z .x-]{1}[0-9]{2}/;
    if(number.match(compare)){
      alert('match');
    }
    else{
      alert('not match');
    }
  });
</script>

Expected output with cases:

1) format should be like this

10X10  or 23X24  or 36X24 or 44X56

like any width by height with uppercase or lowercase 'x'

2) any number with two digits following widthXheight and charecter 'x' can be upper case or lower case

1 Answers

Your regex should be /[0-9]{2}[x|X][0-9]{2}$/

Where:

[0-9] - Matches number in the range between 0 (index 48) and 9 (index 57)

{2} - Quantifier — Matches exactly 2 times

[x|X] - Match the character x or X

$ - Asserts position at the end of a line

$(".clk").click(function(){
  var number=$(".txt_val").val();
  var compare=/[0-9]{2}[x|X][0-9]{2}$/;
  if(number.match(compare)){
    alert('match');
  }
  else{
    alert('not match');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<input type="text" name="txt" class="txt_val" value=""/>
<input type="button" class="clk" value="submit"/>

Related