javascriptjqueryjquery-mask

validating length of the phone on click of submit button


I want to validate the length of the phone field on click of submit button If the length of the phone field is less than 10 then it is supposed to give an error saying "this field should be 10 characters long". This is the HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>

<input id="phone1" class="phone" placeholder="(___) ___-____"/>
<div class="error"></div>
<input id="phone2" class="phone" placeholder="(___) ___-____"/>
<div class="error"></div>
<input id="phone3" class="phone" placeholder="(___) ___-____"/>
<div class="error"></div>

<input style="float: right; margin-bottom:20px" type="submit" id="myBtn1" value="Submit" class="btn btn-primary"  />

this is what I tried to do so far, but it does not work:

$(document).ready(function(e){
  
if(e.target) {
    let value = e.target.value.replace(/\D/g,'');
    if (value.length < 10) {
      $(e.target).next(".error").html('this field should be 10 characters long');
    } else {
      $(e.target).next(".error").html('');
    }
  }
});

I am new to jQuery. Any help will be highly appreciated.


Solution

  • So the issue is that your code is currently running once when the document loads, rather than each time submit is clicked. Also, in the line let value = e.target.value.replace(/\D/g,'');, the e.target here is not any of the inputs.

    Here is some updated code. I added a click event listener on the input, $("#myBtn1").click(function(){...}. Now when this submit input is clicked, we can trigger a function to run. This function will iterate on each input with $(".phone").each(function(){...} and validate their value. The $(this) selector refers to the current phone input field being validated.

    $(document).ready(function(){
      $("#myBtn1").click(function(){
        $(".phone").each(function(){
          let value = $(this).val().replace(/\D/g,'');
          if (value && value.length < 10) {
            $(this).next(".error").html('This field should be 10 characters long');
          } else {
            $(this).next(".error").html('');
          }
        });
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
    <input id="phone1" class="phone" placeholder="(___) ___-____"/>
    <div class="error"></div>
    <input id="phone2" class="phone" placeholder="(___) ___-____"/>
    <div class="error"></div>
    <input id="phone3" class="phone" placeholder="(___) ___-____"/>
    <div class="error"></div>
    
    <input style="float: right; margin-bottom:20px" type="submit" id="myBtn1" value="Submit" class="btn btn-primary"  />