Skip to content
Advertisement

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>

Advertisement

Answer

for email validation, <input type="email"> is enough..

for mobile no use pattern attribute for input as follows:

<input type="number" pattern="d{3}[-]d{3}[-]d{4}" required>

you can check for more patterns on http://html5pattern.com.

for focusing on field, you can use onkeyup() event as:

function check()
{

    var mobile = document.getElementById('mobile');
   
    
    var message = document.getElementById('message');

   var goodColor = "#0C6";
    var badColor = "#FF9B37";
  
    if(mobile.value.length!=10){
       
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
    }}

and your HTML code should be:

<input name="mobile"  id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>
Advertisement