Validating the text field in HTML using javascript

advertisements

I want to validate text field "Username" of the form as per below pasted code. The validation is to make the Username text field mandatory.

The problem which I am facing here is the text fields are not getting validated and onclick of submit button it is directly moving to the next page "index.html" . Can someone suggest me how can I correct this in my below code? I want the validation to happen first and then then if it is passing the validation, then the user can move to next page.

My Code:

<html>
<head>
<script>
//validation for username to be a mandatory field
function ValidateContactForm()
{
    var name = document.ContactForm.userid;

    if (userid.value == "")
    {
        window.alert("Please enter your name.");
        name.focus();
        return false;
    }

</script>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:30pt;
color:#00FF00;>
<strong>Welcome</strong>
</h1>
<form name="login">
Username: <input type="text" name="userid "/><br/>
Password: <input type="password " name="pswrd"/><br/><br/><br/><br/>

</form>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar = form.submit();
}

</SCRIPT>
</HEAD>
<BODY>
<form method="post" action="index.html" name="ContactForm" onsubmit="return ValidateContactForm();">
<input type="submit" value="Submit">
<input type="reset" value="Cancel"/>
</form>
</BODY>
</HTML>


Instead of using custom JavaScript to validate the form (which shouldn't be relied on to actually validate the form as it can be bypassed), you can use the new HTML5 required attribute on your textbox to make it required on the client side.