Home > front end >  Validation for 10 digit mobile number and Showing Color On Input If Invalid
Validation for 10 digit mobile number and Showing Color On Input If Invalid

Time:08-02

I need the red color to appear on the input field when input is not up to 10 digits and the color should turn green when digits are up to 10.

Please see my code below Thanks;

function check()
{

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

   var goodColor = "#03b800";
    var badColor = "#f00a0a "; 
  
    if(mobile.value.length!=10){
       
        mobile.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "required 10 digits, match requested format!"
        }
        else if(mobile.value.length <10){
       
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
    }}
<input name="mobile"  id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>

CodePudding user response:

Your logic has an error.


   if (mobile.value.length === 10){
       
        mobile.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Good job! You entered it correctly"
   }
   else {
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
   }

CodePudding user response:

One other thing, we live in a mobile focused world now and onkeyup is not exactly friendly to most mobile browsers specs.

I would remove the attribute

<input name="mobile" id="mobile" type="number" required return false;" ><span id="message"></span>

And bind to the on change event.

$('#mobile').change(function(){ check(); });

  • Related