0

i am trying to validate phone number length using jquery, when user start typing itself it should display, i did 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>

however this doesnt work, can anyone please tell me what is wrong in here, thanks in advance

TBC
  • 101
  • 7
  • First of all, you should not be using the `var` keyword as a variable _name_. – CBroe May 11 '23 at 09:01
  • Second, you are passing the _value_ the field contains in `validatePhone(phone)`, but then you are trying to access `phone.value` inside that function, which makes no sense - a _string_ does not have a `value` property. – CBroe May 11 '23 at 09:03
  • `result1.text(var);` - naming issue aside, `var` does not exist in that scope. – CBroe May 11 '23 at 09:05

1 Answers1

1

I cleaned up your code a bit, it was mostly ok but you had some small syntax errors and logic errors. Also I suggest using the label tag. The code can be written even 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

<label for="phone">Phone Number <span style="color:red">*</span></label>
<input type="number" class="form-control" required id="phone" name="phone">
<span id="result1"></span>

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

Kokodoko
  • 26,167
  • 33
  • 120
  • 197