[javascript] Validation for 10 digit mobile number and focus input field on invalid

I need the code for validating email and mobile number in jQuery and also focus() on that particular field where validations are not satisfied.

This is my query

<form name="enquiry_form" method="post" id="enquiry_form">

    Full Name *
    <input class="input-style" name="name"  id="name" type="text" required> 
    Email *
    <input class="input-style" name="email"  id="email" type="email" required>
    Phone * 
    <input name="mobile"  id="mobile" type="number" required>

    <input type="submit" value="SUBMIT"  id="enq_submit"">

</form>

This question is related to javascript php jquery html

The answer is


Above code is correct but mobile validation is not perfect.

i modified as

$('#enquiry_form').validate({
  rules:{
  name:"required",
  email:{
  required:true,
  email:true
  },
  mobile:{
      required:true,
  minlength:9,
  maxlength:10,
  number: true
  },
  messages:{
  name:"Please enter your username..!",
  email:"Please enter your email..!",
      mobile:"Enter your mobile no"
  },
  submitHandler: function(form) {alert("working");
  //write your success code here  
  }
  });

After testing all answers without success. Some times input take alpha character also.

Here is the last full working code with only numbers input also keeping in mind backspace button key event for user if something number is incorrect.

_x000D_
_x000D_
$("#phone").keydown(function(event) {_x000D_
  k = event.which;_x000D_
  if ((k >= 96 && k <= 105) || k == 8) {_x000D_
    if ($(this).val().length == 10) {_x000D_
      if (k == 8) {_x000D_
        return true;_x000D_
      } else {_x000D_
        event.preventDefault();_x000D_
        return false;_x000D_
_x000D_
      }_x000D_
    }_x000D_
  } else {_x000D_
    event.preventDefault();_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input name="phone" id="phone" placeholder="Mobile Number" class="form-control" type="number" required>
_x000D_
_x000D_
_x000D_



function is_mobile_valid(string_or_number){
            var mobile=string_or_number;
            if(mobile.length!=10){
                return false;

            }
            intRegex = /[0-9 -()+]+$/;
            is_mobile=true;
            for ( var i=0; i < 10; i++) {
                if(intRegex.test(mobile[i]))
                     { 
                     continue;
                     }
                    else{
                        is_mobile=false;
                        break;
                    }
                 }
            return is_mobile;

}

You can just check by calling the function is_mobile_valid(your_string_of_mobile_number);


$().ready(function () {

    $.validator.addMethod(
            "tendigits",
            function (value, element) {
                if (value == "")
                    return false;
                return value.match(/^\d{10}$/);
            },
            "Please enter 10 digits Contact # (No spaces or dash)"
            );

    $('#frm_registration').validate({
        rules: {
            phone: "tendigits"
        },
        messages: {
            phone: "Please enter 10 digits Contact # (No spaces or dash)",

        }

    });

})

you can also use jquery for this

  var phoneNumber = 8882070980;
            var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;

            if (filter.test(phoneNumber)) {
              if(phoneNumber.length==10){
                   var validate = true;
              } else {
                  alert('Please put 10  digit mobile number');
                  var validate = false;
              }
            }
            else {
              alert('Not a valid number');
              var validate = false;
            }

         if(validate){
          //number is equal to 10 digit or number is not string 
          enter code here...
        }

_x000D_
_x000D_
var message = document.getElementById('contact-error');_x000D_
$('#contact').focusout(function(){_x000D_
 if(!$(this).val().match('[0-9]{10}'))  {_x000D_
  $('#contact-error').addClass('contact-message');_x000D_
        message.innerHTML = "required 10 digits, match requested format!";_x000D_
    }else {_x000D_
     $('#contact-error').removeClass('contact-message');_x000D_
     message.innerHTML = "";_x000D_
    }_x000D_
})
_x000D_
.contact-message {_x000D_
    display: block;_x000D_
    margin-bottom: 20px;_x000D_
    color: #cc0033;_x000D_
}
_x000D_
<input type="text" id="contact" required>_x000D_
<span id="contact-error"></span>
_x000D_
_x000D_
_x000D_


I used $form.submit() as it keeps html input validation.

Also I used input type tel as it supported by mobile browsers, only display numeric keypad.

<input type="tel" minlength="10" maxlength="10" id="mobile" name="mobile" title="10 digit mobile number" required>


$('#mob_frm').submit(function(e) {
            e.preventDefault();
            if(!$('#mobile').val().match('[0-9]{10}'))  {
                alert("Please put 10 digit mobile number");
                return;
            }  

        });

function isMobileNumber(evt, sender) { // Allows only 10 numbers // ONKEYPRESS FUNCTION
//evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
var NumValue = $(sender).val();
if (charCode > 31 && (charCode < 48 || charCode > 57)) {//|| NumValue.length > 9) {
    return false;
}
return true;}


function isProperMobileNumber(txtMobId) { //// VALIDATOR FUNCTION   
var txtMobile = document.getElementById(txtMobId);
if (!isNumeric(txtMobile.value)) { $(txtMobile).css("border-color", "red"); return false; }
if (txtMobile.value.length < 10) {
    $(txtMobile).css("border-color", "red");
    return false;
}
$(txtMobile).css("border-color", "")
return true; }

function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n) }

Use jquery validator in your script tag DEMO

<script src="js/jquery.validate.min.js"></script> 

and validate your element by like this

   <form name="enquiry_form" method="post" id="enquiry_form">

    Full Name *
    <input class="input-style" name="name"  id="name" type="text"/>
    <br>
    Email *
    <input class="input-style" name="email"  id="email" type="email"><br>
    Phone * 
        <input id="mobile" name="mobile"  id="mobile"></input><br>

    <input type="submit" value="SUBMIT"  id="enq_submit">

</form>

 $('#enquiry_form').validate({
      rules:{
      name:"required",
      email:{
      required:true,
      email:true
      },
      mobile:{
          required:true,
      minlength:9,
      maxlength:10,
      }
      },
      messages:{
      name:"Please enter your username..!",
      email:"Please enter your email..!",
          mobile:"Enter your mobile no"
      },

      submitHandler: function(form) {
alert("working");
      //write your success code here  
      }
      });


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment