Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to create a validation error message without using alert

I am looking to make a simple form validation error message that displays under the username field.

I cannot seem to 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 validation script:

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
    }
like image 214
jhs546 Avatar asked Dec 03 '12 18:12

jhs546


2 Answers

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>
like image 127
Gaurab Pradhan Avatar answered Sep 24 '22 22:09

Gaurab Pradhan


You need to stop the submission if an error occured:

HTML

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

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}
like image 27
Zoltan Toth Avatar answered Sep 24 '22 22:09

Zoltan Toth