javascripthtmlformsvalidation

Validation for 10 digit mobile number and Showing Color On Input If Invalid


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>


Solution

  • Your logic has an error.

    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 = "Good job! You entered it correctly"
      } else {
        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>

    
       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!"
       }