Validate function is not triggered and form is submitted - javascript

File with the code bellow is "newrecord.html" presents the form for submitting some record entries that suppose to do the a db and after the users submits the form the validation function is called to check with it's functions the user input.
The form is loaded as normal but after the form is submitted the validation function is not being called and just redirects to to the "newRecord.php"
<!DOCTYPE html>
<html>
<head>
<title>insert New Record</title>
<style>
.recordform {
border:1px solid #999999;
font: normal 14px helvetica;
color: #444444
}
</style>
<script>
function validateAuthor(field)
{
return(field=="") ? "No Author Entered".\n" : ""
}
function validateTitle(field)
{
return(field=="") ? "No Title Entered".\n" : ""
}
function validateCategory(field)
{
return(field=="") ? "No Category Entered".\n" : ""
}
function validateYear(field)
{
if (field=="") return "No Year Entered.\n"
else if (field.length>4)
return "Enter Valid Year value (YYYY).\n"
else if (/[^0-9]/.test(field))
return "Enter only numbers 0-9"
return ""
}
function validateIsbn(field)
{
if (field=="") return "No Isbn Entered.\n"
else if (/[^0-9]/.test(field))
return "Enter only numbers"
return ""
}
function validate(form)
{
fail=validateAuthor(form.author.value)
fail+=validateTitle(form.title.value)
fail+=validateCategory(form.category.value)
fail+=validateYear(form.year.value)
fail+=validateIsbn(form.isbn.value)
if (fail==""){
return true;
}else{
alert(fail);
return false}
}
</script>
</head>
<body>
<table border="0" cellpading="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Insert New Record</th>
<form method="post" action="newRecord.php" onsubmit="return validate(this)">
<tr><td>Author</td>
<td><input type="text" maxlength="25" name="author"</td></tr>
<tr><td>Title</td>
<td><input type="text" maxlength="25" name="title"</td></tr>
<tr><td>Category</td>
<td><input type="text" maxlength="25" name="category"</td></tr>
<tr><td>Year</td>
<td><input type="text" maxlength="25" name="year"</td></tr>
<tr><td>Isbn</td>
<td><input type="text" maxlength="25" name="isbn"</td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Insert New Record"></td></tr>
</form>
</table>
</body>
</html>

Related

Using javascript for form validation in HTML

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();
}

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>

Javascript Validation Inconsistent

In the codes below, both functions and callings are quite similar.
Why is it that the JavaScript validation alert works in the code below:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form 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"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
but doesn't work in this one:
<!DOCTYPE html>
<html>
<head>
<title> Untitled</title>
<script type='text/javascript'>
}
function validate()
{
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<input type="submit" value="Submit"/> <br>
</form>
</body>
</html>
Probably because you've got a leading '}' in the code in the second example.
<script type='text/javascript'>
} // <- this is going to cause a syntax error
function validate()
{
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
return( true );
}
</script>
Try fixing that and see if it works. If you're running things in a browser, check the JavaScript console for errors.

Need a javascript function to reset text to black on button click

I am designing an exam entry form to take a users name, subject, exam number and level (GCSE, AS, A2), if the user inputs a value wrong then the name of the field turns red, I need a JavaScript function to change the text back to black and i am having some trouble with this. Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
if(result) document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
if(result) document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+="You must enter the exam number \n";
if(result) document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
if (document.ExamEntry.examnumber.value.length!=4) {
msg+="Your exam number must be exactly 4 digits \n";
if(result) document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
if(msg != ""){
alert(msg);
return result;
}
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null) {
alert('Please choose an option');
return false;
}
else {
return confirm('You have chosen '+checked.value+' is this correct?');
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" placeholder='Name' /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" placeholder='Subject' /></td>
</tr>
<tr>
<td id="examnumber">Exam Number</td>
<td><input type="text" name="examnumber" size="4" maxlength="4" placeholder='No.'/></td>
</tr>
<tr>
<td><input type="radio" id="examtypeGCSE" name="examtype" value="GCSE" /> : GCSE<br/>
<input type="radio" id="examtypeA2" name="examtype" value="A2" /> : A2<br/>
<input type="radio" id="examtypeAS" name="examtype" value="AS"/> : AS<br/>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
In beginning of the function validateForm() set all the texts to black. Cuz everytime you enter the validate function it will set all the texts to black, then enter the if statements if the conditions is correct.
for example:
function validateForm() {
document.getElementById('name').removeAttribute('style');
....
....
...
}
but then the color wont change until you click the button.
Else add an onchange function on the textboxes to check the validation.

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

Categories