Using javascript for form validation in HTML - javascript

I have been looking at some examples of form validation, where an invalid input will stop the user before proceeding to the next page. The way I have seen this done many times is using the event.preventDefault() function, but it just doesn't seem to be working for me. I'm not sure if the javascript function is wrong, or maybe it is just not being read at all. When I send in an invalid input it goes through to the next page anyway.
Here is my HTML code:
Header:
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="3.css"/>
<script type="text/javascript" src="3.js"></script>
<title>Login</title>
Body:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="submit" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
and here is the referenced 3.js code:
document.getElementById("loginForm").addEventListener("submit", loginFunction, false);
function loginFunction(event)
{
var valid= true;
var elements= event.currentTarget;
var email= elements[0].value;
var pass= elements[1].value;
var regexEmail= /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass= /^(\S*)?\d+(\S*)?\W+$/;
var emailError= document.getElementById(emailError);
var passError= document.getElementById(passError);
if (email == null || email == ""){
emailError.innerHTML= "Email is empty";
valid= false;
}
else if (regexEmail.test(email) == false){
emailError.innerHTML= "Incorrect Email format";
valid= false;
}
if (pass == null || pass == ""){
passError.innerHTML= "Password is empty.";
valid = false;
}
else if (regexPass.test(pass) == false) {
passError.innerHTML= "Incorrect password format";
valid = false;
}
else if (pass.length < 8){
passError.innerHTML= "Password is too short, must be 8+ characters";
valid= false;
}
if (valid == false){
event.preventDefault();
}
}
Can anyone explain where i've made my error?

This should do the trick:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="button" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
And this:
document.getElementById('loginSubmit').addEventListener('click',loginFunction,false);
function loginFunction()
{
var valid=true;
var elements=event.currentTarget;
var email=elements[0].value;
var pass=elements[1].value;
var regexEmail=/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass=/^(\S*)?\d+(\S*)?\W+$/;
var emailError=document.getElementById(emailError);
var passError=document.getElementById(passError);
if(email==null||email=='')
{
emailError.innerHTML='Email is empty';
valid=false;
}
else if(regexEmail.test(email)==false)
{
emailError.innerHTML='Incorrect Email format';
valid=false;
}
if(pass==null||pass=='')
{
passError.innerHTML='Password is empty.';
valid=false;
}
else if(regexPass.test(pass)==false)
{
passError.innerHTML='Incorrect password format';
valid=false;
}
else if(pass.length<8)
{
passError.innerHTML='Password is too short, must be 8+ characters';
valid=false;
}
if(!valid)
{
return
}
document.getElementById('LoginForm').submit();
}

Related

Uncaught ReferenceError: validateForm is not defined at HTMLInputElement.onclick

why do I have this problem? I'm trying to get an output to the user name in the site. but it keeps giving me this problem!
I ant it to write me that the user name is not correct when im starting with a number or it is blanked at all- it gives me nothing.
please help me I am sitting on this above an hour:((
Snippet
function validateForm() {
var res = true;
res = userNameVal() && res;
return res;
}
function userNameVal() {
var userName = document.getElementById("username").value;
var msgBox = document.getElementById("userNameCheck");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter user name";
msgBox.style.color = "red"
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "User name must start with a letter ";
msgBox.style.color = "red";
return false;
}
msgBox.innerHTML = "";
return true;
}
<form id="form1" method="post" onsubmit="return validateForm()">
<table class="table3">
<tr>
<td>
<label for="username">User Name:</label>
</td>
<td>
<input type="text"
name="username"
id="username"
onchange="userNameVal()" />
</td>
<td>
<div id="userNameCheck"></div>
</td>
</tr>
<tr>
<td><input type="button"
value="submit"
onclick="return validateForm()"/>
<input type="reset" value="reset" />
</td>
<td></td>
<td></td>
</tr>
</table>
</form>

Javascript validation script

I am struggling to understand where there is a mistake.
After many tries, I tend to think that it's something about overalcheck()...
The append, clearelement and writeto are the additional mini functions and they are totally fine.
So, this script checks the form, and if everything is ok, opens a new page. However, if a field is empty or has a wrong type, it shows the relative error message (or a list of error messages).
I made a lot of variations, sometimes it opens without a completed form (like the code below), sometimes it shows the error message for 1 field only and then, and even if you complete all fields, it still doesnt open a new page.
I would appreciate your help.
<script>
function overallcheck ()
{
if(!checkname() || !checkemail() || !checkjob())
{
writeTo("problemArea","Error messages area");
if(!checkname())
writeTo("problemArea","Please insert a valid name");
if(!checkemail())
writeTo("problemArea","Please insert a valid email");
if(!checkjob())
writeTo("problemArea","Please insert your job");
return false;
}
return true;
}
function checkname()
{
clearElement("problemArea");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname))
return false;
}
function checkemail()
{
clearElement("problemArea");
var mail = document.forms['form'].Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1)
return false;
}
function checkjob()
{
clearElement("problemArea");
var i;
for (i=0;i<4;i++)
{
if (document.forms['form'].job[i].checked) {return true;}
}
return false;
}
</script>
<body>
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b> </td>
<td> <input type="text" name="fullname" size="20" placeholder="Enter a valid name"/> </td>
</tr>
<tr>
<td><b><p> E-mail: </p></b></td>
<td><input type="email" name="email" maxlength="15" size = "20" placeholder="Enter a valid email address"/> </td>
</tr>
<tr>
<p><td><b><p>bla?</td></p>
<td>1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/><div id="problemArea"> </div>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>
</body>
</html>
Track each error type with it's own div. Wrap overallcheck in a try catch to and alert errors. This helped find the "Email" error.
function writeTo(id, msg) {
document.getElementById(id).innerHTML += "<p>" + msg + "</p>";
}
function clearElement(id) {
document.getElementById(id).innerHTML = "";
}
function overallcheck() {
try {
if (!checkname() || !checkemail() || !checkjob()) {
if (!checkname())
writeTo("problem_fullname", "Please insert a valid name");
if (!checkemail())
writeTo("problem_email", "Please insert a valid email");
if (!checkjob())
writeTo("problem_blah", "Please insert your job");
return false;
}
return true;
} catch (err) {
alert(err);
}
}
function checkname() {
clearElement("problem_fullname");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname)) {
return false;
}
return true;
}
function checkemail() {
clearElement("problem_email");
var mail = document.forms['form'].email.value; //Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1) {
return false;
}
return true;
}
function checkjob() {
clearElement("problem_blah");
var i;
for (i = 0; i < 4; i++) {
if (document.forms['form'].job[i].checked) {
return true;
}
}
return false;
}
td {
vertical-align: text-top;
}
.problem {
color: red;
}
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b>
</td>
<td>
<input type="text" name="fullname" size="20" placeholder="Enter a valid name" />
<div id="problem_fullname" class="problem"></div>
</td>
</tr>
<tr>
<td><b><p> E-mail: </p></b>
</td>
<td>
<input type="email" name="email" maxlength="15" size="20" placeholder="Enter a valid email address" />
<div id="problem_email" class="problem"></div>
</td>
</tr>
<tr>
<p>
<td><b><p>bla?</td></p>
<td>
1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
<div id="problem_blah" class="problem"> </div>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>

Display form values to next HTML page

hi i want to display all my form data being entered by the user to the next HTML page, but the only thing i m using javascript for form validation and HTML.
any help would be highly appreciated.
<head>
<link rel="stylesheet" href="main.css" type="text/css">
<title>A simple Form Validation</title>
</head>
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var businessname = document.getElementById('businessname');
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var fax = document.getElementById('fax');
// Check each input in the order that it appears in the form!
if(isAlphabet(businessname, "Please enter only letters for your Businessname")){
if(isAlphabet(firstname, "Please enter only letters for your name")){
if(isAlphabet(lastname, "Please enter only letters for your last name")){
if(isNumeric(phone, "Please enter numbers for your phone no")){
if(isNumeric(fax, "Please enter numbers for your fax")){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form onsubmit='return formValidator()' method="POST" action="index.htm">
<table>
<tbody>
<div id="header-container">
<div id="header">
<div id="logo">
<img src="bus.jpg" />
</div>
<div id="navbar">
<ul id="nav">
<li><a id="Home" alt="home">Home</a></li>
<li><a id="contactus" alt="contact Us">Contact Us</a></li>
</ul>
</div><br><br>
<tr>
<td><label for="Business Name">Business Name:</label></td>
<td><input name="Business Name" id="businessname" size="30" maxlength="40" type="text"></td>
</tr>
<tr>
<td><label for="First Name">First Name:</label></td>
<td><input name="First Name" id="firstname" size="30" maxlength="40" type="text"></td>
</tr>
<tr>
<td><label for="Last Name">Last Name:</label></td>
<td><input name="Last Name" id="lastname" size="30" maxlength="40" type="text"></td>
</tr>
<tr>
<td><label for="Email">Email:</label></td>
<td><input name="Email" id="email" size="30" maxlength="40" type="text"></td>
</tr>
<tr>
<td><label for="Phone">Phone:</label></td>
<td><input name="Phone" id="phone" size="30" maxlength="40" type="text"></td>
</tr>
<tr>
<td><label for="Fax">Fax:</label></td>
<td><input name="Fax" id="fax" size="30" maxlength="40" type="text"></td>
</tr>
</tbody>
</table>
<input type='submit' value='Submit' />
</form>
this is my form and i did validation over it... now I want to display the form values on next page...
If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.
In the form, add a method="GET" attribute:
<form action="your.html" method="GET">
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
When they submit this form, the user will be directed to an address which includes the name value as a parameter. Something like:
http://www.example.com/display.html?name=XYZ
You should then be able to parse the query string - which will contain the name parameter value - from JavaScript, using the window.location.search value:
// from your.html
document.getElementById("write").innerHTML = window.location.search;
this can help you...`form fill on next html page
May be this can help you http://wiseadvance.com/teaching/web_design/tutorials/get_data_from_forms/
Better use any server side scripting to display data.
You have to use either a Server side script or use HTML5 LocalStorage

Validating multiple fields in a form

I was doing the testing for the first time. I read the this code and made one of my own from it. The thing is that its not giving any error even if the fields are left empty.
Here is my fiddle.
Please help out. Thanks.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
{function validateForm()
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
​
Fixed code: jsfiddle
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
if (y==null || y=="") {
alert("Password name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
<html>
Be careful of where you place your braces. Additionally, it is advantageous to use the console on your browser to identify some errors and fixed them.
​
Your brace should be after function validateForm() and after the if, and at the end of the function. Overall, the braces are screwed in this example.
Lay your code out so the opening and closing braces match up and make sense to you.
You missed some braces {} and one was in the wrong spot.
Hope this works:
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
}
You misplaced the braces { } for validation of password. Place them after if clause.
I found it on Internet after a long time searching.. But it works just perfect..
The html code
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
the javascript
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
and the function for email validation
<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
you can check it online here

Java script not running

Here is my html code with javascript validations.... HTML elements are showing well javascript function is not working.....
<html>
<head>
<title>SIGNUP</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="style/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function valid(fname,sname,login,name,tstest,mailf,mails){
var namef=fname.value;
var names=sname.value;
var logn=login.value;
var name1=name.value;
var ts=tstest.value;
var mailf=mail1.value;
var mails=.mail2.value;
if(namef=="") <!-- validating the field first name-->
{
window.alert("please enter name.");
fname.focus();
}
else if(names=="")<!-- validating the field second name-->
{
window.alert("please enter password");
sname.focus();
}
else if(names<=6)
{
window.alert("Password should be more than 6 characters");
sname.focus();
}
else if(logn=="")<!-- validating the login field-->
{
window.alert("please enter email.");
login.focus();
}
else if(name1=="")<!-- validating the password field-->
{
window.alert("please enter confirm password.");
name.focus();
}
else if(name1!=names)
{
window.alert("Password Mismatch");
name.focus();
}
else if(ts=="")<!-- validating the date field-->
{
alert("please enter contact number.");
tstest.focus();
}
else if(ts<10)
{
alert("Contact Number Should be Minimum 10 numbers");
tstest.focus();
}
else if(mailf=="")<!-- validating the mail field-->
{
alert("please enter qualification.");
mail1.focus();
}
else if(mails=="")<!-- validating the 2nd mail field-->
{
alert("please enter interested in.");
mail2.focus();
}
}
}
</script>
</head>
<body>
<center>
<div id="border"><div id="header">
<div id="logo-bg">
<div class="name">Ayansys</div>
<div class="tag">COMPANY SLOGAN</div>
</div>
</div>
<div>
<h1>SIGNUP FORM</h1>
<form name="sign" onsubmit="valid(fname,sname,login,pwd,tstest,mail1,mail2)" >
<table name="signuptable">
<tr><td>FIRST NAME</td><td><input type="text" name="fname" size="50"/></td></tr>
<tr><td>LAST NAME</td><td><input type="text" name="sname" size="50"/></td></tr>
<tr><td>DESIRED LOGIN NAME</td><td><input type="text" name="login" size="50"/></td></tr>
<tr><td>PASSWORD</td><td><input type="password" name="pwd" size="50"/></td></tr>
<tr><td>RE-TYPE PASSWORD</td><td><input type="password" name="repwd" size="50"/></td></tr>
<tr><td>GENDER</td><td><input type="radio" name="gender" value="Male"/>Male<input type="radio" name="gender" value="FeMale"/>Female</td></tr>
<tr><td>DATE OF BIRTH</td><td><form name="tstest">
<input type="text" readonly size="47" name="timestamp" value="">
<img src="cal.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp">
</form></td></tr>
<tr><td>MAIL ID</td><td><input type="text" name="mail1" size="30">#<input type="text" name="mail2" size="11"></td></tr>
<tr><td>EMPLOYEE ID</td><td><input type="text" name="eid" size="50"></td></tr>
<tr><td>TYPE OF USER</td><td><input type="radio" name="manager"/>Manager<input type="radio" name="manager"/>SeniorManager</td></td></tr>
<tr><td>ADDRESS</td><td><textarea rows="9" cols="40" name="addr"></textarea></td></tr>
<tr><td>MOBILE NUMBER</td><td><input type="text" size="50" name="mobile"></td></tr>
<tr><td></td><td><input type="submit" name="sign" value="SUBMIT"> <input type="reset" name="cancel" value="CANCEL"/></td></tr>
</table>
</div>
</form>
</br><div>Designed by:STUDY CENTER</div>
</div>
</center>
</body>
line 13, you have a "dot"
mails=.mail2.value;
line 66 syntax error you had a wrong placed brace
try removing the dot and the brace and see if it works as expeted
pulse window.alert() , you only need to use alert()
and your redeclaring you variables
your onsubmit argument mail2 differs from the expeted one mails

Categories