Home  >  Q&A  >  body text

Validating phone number length using jquery doesn't work

I'm trying to validate the phone number length using jquery, when the user starts typing their own content it should be displayed, I executed the following code:

function validatePhone(phone) {
  if (phone.value.length <= 10 && phone.value.length >= 5) {
    let
    var = 'Yes';
    return var;
  } else {
    let
    var = 'No';
    return var;
  }
}

function validate() {
  let result1 = $("#result1");
  let phone = $("#phone").val();
  result1.text("");


  if (validatePhone(phone)) {
    result1.text(var);
    result1.css("color", "green");
  }
  return false;
}
jQuery(function($) {
  $("#phone").on("input", validate);
});
<input type="number" class="form-control"  id="phone" name="phone">
<span class="label">Phone Number<span style="color:red">*</span> <span id="result1"></span></span>

But this doesn't work, can someone tell me what's wrong here, thanks in advance

P粉520545753P粉520545753184 days ago295

reply all(1)I'll reply

  • P粉216807924

    P粉2168079242024-03-31 11:09:27

    I cleaned up your code a bit and it's basically fine, but you have some minor syntax errors and logic errors. I also recommend using the label label. The code can be written shorter if you want!

    function validatePhone(phone) {
      if (phone.length <= 10 && phone.length >= 5) {
        return true;
      } else {
        return false;
      }
    }
    
    function validate() {
      let result1 = $("#result1");
      let phone = $("#phone").val();
      result1.text("");
    
    
      if (validatePhone(phone)) {
        result1.text("great!");
        result1.css("color", "green");
      } else {
        result1.text("please input phone number");
        result1.css("color", "red");
      }
    }
    
    jQuery(function($) {
      $("#phone").on("input", validate);
    });
    

    HTML

    
    
    
    

    I also suggest you take a look at the css:valid rules! https://developer.mozilla.org/en-US/docs /Web/CSS/:valid

    reply
    0
  • Cancelreply