JS determines whether the form input is null of sample code

  • 2020-03-30 01:03:00
  • OfStack


//Remove Spaces on both sides of the input string
function trim(s) {   
   var count = s.length;   
   var st    = 0;       // start   
   var end   = count-1; // end   

   if (s == "") return s;   
   while (st < count) {   
     if (s.charAt(st) == " ")   
       st ++;   
     else  
       break;   
   }   
   while (end > st) {   
     if (s.charAt(end) == " ")   
       end --;   
     else  
       break;   
   }   
   return s.substring(st,end + 1);   
 } 

Suppose the form looked like this:

<form action="testnew.html" name="form1">   
  username: <input type="text" name="name">   
  password: <input type="password" name="pwd">   <br>   
  <input type="submit" value=" submit " onclick="isEmpty()">   
</form>

To determine whether the input is null, the function can be defined as follows:

function isEmpty(){   
    //Form1 is the name property & NBSP; in the form;  
    var _form = document.form1;   

    if(trim(_form.name.value)==""){   
        alert(" The username cannot be empty !");           
        return false;   
    }   
    if(trim(_form.pwd.value)==""){   
        alert(" The password cannot be empty !");          
        return false;   
    }  
    return true;
}


Related articles: