0

I was trying to validate my phone number. Everything is working except the validate 10 digit part

if ($(".phone").val() == "") {
    phoneerror = "Please enter phone number";
} else if (!($.isNumeric($(".phone").val())) && $(".phone").val() != "") {
    phoneerror = "this field cannot contain letters";
} else if ($(".phone").val().length !== 10) {
    phoneerror = "Must be 10 Digits";
} else {
    phoneerror = "";
}

console.log(phoneerror);
<script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
<input type="text" class="phone" value="12345">

can someone please tell me what is the wrong with my code

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
Hi Im Naru7o
  • 72
  • 2
  • 12
  • 1
    I think this would be easier with a regular expression (subject to any number of limitations about what is actually a valid phone number). [See this question](https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript). – KevinO Oct 04 '18 at 04:55
  • 1
    Can you explain what is the issue now, i checked it in Codepen and it is working perfectly now. https://codepen.io/nisaifudeen/pen/PyNmaY – saifudeen ni Oct 04 '18 at 05:13
  • Seems to working. – ssc-hrep3 Oct 04 '18 at 06:38
  • @KevinO A 10 digit phone number sounds like NANP format, for which it would indeed make sense to test it with a RegExp (which could include spacer characters). – Dormilich Oct 04 '18 at 08:41

1 Answers1

0

Please check this sample. You should position number length before other validations also you can use maxlength html attribute.

function validatePhone(){
if($(".phone").val() == ""){
      phoneerror = "Please enter phone number";
          } else if ($(".phone").val().length !== 10){
        phoneerror = "Must be 10 Digits";
        } else if(!($.isNumeric($(".phone").val())) && $(".phone").val() != ""){
            phoneerror = "this field cannot contain letters";

        }else {
            phoneerror = "";
        }
        console.log(phoneerror);
        return phoneerror;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="phone" type="text" onkeyup="validatePhone(this);" maxlength="10"/>
Nezir
  • 6,727
  • 12
  • 54
  • 78