validating html form with javascript -


basically want validate form, i'm trying document.getelementbyid(); not working can me , why not going way i'm trying.

 <form name="simple" action="post">              <label for="name">                 name:             </label>             <input type="text" id="demo" class="form-control" onsubmit="validate();"><br>              <label for="email">                 e-mail:             </label>             <input type="email" id="email" class="form-control"><br>              <label for="pwd">                 password:             </label>             <input type="password" id="pwd" class="form-control"><br>              <label for="phone">                 phone:             </label>             <input type="text" id="phone" class="form-control"><br>              <input type="button" type="submit" value ="submit" class="form-control" onclick="validate();" >              <input type="button" type="reset" value ="reset" class="form-control">          </form>         <script>           function validate()     {         var txt = document.getelementbyid("demo");         alert(txt);         if(txt == " " || txt == null)         {             alert("name can't left blank");         }      }         </script> 

in order value of field, have access .value field of element, so: document.getelementbyid('demo').value.

in order catch submit event, must set onsubmit function on form, so:

document.getelementbyid("myform").onsubmit = validate; 

inside validate function, have call return false; in case input invalid:

if (txt === null || txt.trim() === '') {     alert("name can't left blank");     return false; } 

also, if you're doing validation, pattern , required attributes of input element. modern browsers respect rules set these attributes, , wouldn't have manually validate it.

https://www.w3schools.com/tags/att_input_pattern.asp https://www.w3schools.com/tags/att_input_required.asp


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -