Search code examples
javascriptjqueryhtmljavaquery

jQuery Click Function, input value length and pattern


I have a problem, that I'm struggling with since 2 days. I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:

    $("#start").click(function(){ // click func
    if ($.trim($('#phonenr').val()) == ''){
     $("#error").show();

I tried adding:

     if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)

But it just won't work. Any help would be appreciated. Also please tell me how can I make it allow only numbers?

Thank you!

Final code, with help of @Saumya Rastogi. $("#start").click(function(){

    var reg = /^\d+$/;
    var input_str = $('#phonenr').val();
   chopped_str = input_str.substring(0, input_str.length - 1);
   if(!reg.test(input_str)) {
    $("#error").show();
    return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
  $("#error").show();
} else {

Solution

  • You can make your validation work.

    You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:

    $(function() {
    	$('#btn').on('click',function(e) {
      	var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
        var input_str = $('#phonenr').val();
        chopped_str = input_str.substring(0, input_str.length - 1);
        if(!reg.test(input_str)) {
        	$('label.error').show();
            return;
        }
        if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
          $('label.error').show();
        } else {
          $('label.error').hide();
        }
      });
    })
    label.error {
      display: none;
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="phonenr" type="text" value=""><br>
    <label class='error'>Invalid Number</label>
    <br><br>
    <button id="btn">Click to Validate</button>

    Hope this helps!