Javascript how to create validation error message without using alert

I want to make a simple form validation error message that appears below the username field.

I can’t figure it out.

<form name ="myform" onsubmit="validation()"> Username: <input type ="text" name="username" /><br /> <input type ="submit" value="submit" /> <div id ="errors"> </div> </form> 

Here is my script check:

 function validation(){ if(document.myform.username.value == ""){ //checking if the form is empty document.getElementById('errors').innerHTML="*Please enter a username*"; //displaying a message if the form is empty } 
+6
source share
3 answers

You need to stop sending if an error occurs:

HTML

 <form name ="myform" onsubmit="return validation();"> 

Js

 if (document.myform.username.value == "") { document.getElementById('errors').innerHTML="*Please enter a username*"; return false; } 
+11
source

Javascript

 <script language="javascript"> var flag=0; function username() { user=loginform.username.value; if(user=="") { document.getElementById("error0").innerHTML="Enter UserID"; flag=1; } } function password() { pass=loginform.password.value; if(pass=="") { document.getElementById("error1").innerHTML="Enter password"; flag=1; } } function check(form) { flag=0; username(); password(); if(flag==1) return false; else return true; } </script> 

HTML

 <form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)"> <div id="error0"></div> <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()"> controls"> <div id="error1"></div> <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()"> <button type="submit" class="btn">Sign in</button> </div> </div> </form> 
+2
source

I highly recommend you start using jQuery. Your code will look like this:

 $(function() { $('form[name="myform"]').submit(function(e) { var username = $('form[name="myform"] input[name="username"]').val(); if ( username == '') { e.preventDefault(); $('#errors').text('*Please enter a username*'); } }); }); 
0
source

All Articles