Why does my JavaScript seems to not run in my HTML - javascript

Sorry for any formatting error, first time posting.
Sorry if similar of this is already answered, I couldn't find it anywhere (or I'm just bad at searching).
I'm doing a page to register user to my website, my javascript doesn't work and I can't find what's wrong with it.
My html file does not display the alertbox which supposed to run if I leave my box empty, putting in the wrong characters, etc.
registration.html
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>Registration Form</title>
</head>
<body onLoad="document.registration.userID.focus();">
<h1>Registration Form</h1>
<form name="registration" onSubmit="return validation();">
<label for="userID">User ID</label><br><input id="userID" name="userID" placeholder="Enter your ID" type="text"/><br>
<label for="userPass">Password</label><br><input id="userPass" name="userPass" placeholder="Enter your password" type="password" /><br>
<label for="userName">Username</label><br><input id="userName" name="userName" placeholder="Enter your username" type="text" /><br>
<label for="addr">Address</label><br><input id="addr" name="addr" placeholder="eg. Tamara Residence" type="text" /><br>
<label for="ctry">Country</label><br><select id="ctry" name="ctry">
<option value="DEF">Please select your country</option>
<option value="MY">Malaysia</option>
<option value="IN">India</option></select><br>
<label for="zip">Zip Code</label><br><input id="zip" name="zip" placeholder="eg. 25565" type="text" /><br>
<label for="email">Email</label><br><input id="email" name="email" placeholder="eg. nikfarisaiman109#gmail.com" type="text" /><br>
Sex<br>
<input type="radio" id="1" name="sex" value="1">
<label for="1">Male</label><br>
<input type="radio" id="2" name="sex" value="2">
<label for="2">Female</label><br>
Language<br>
<input type="checkbox" id="EN" name="EN" value="English">
<label for="EN">English</label><br>
<input type="checkbox" id="MY" name="MY" value="Malay">
<label for="MY">Malay</label><br>
<label for="about">About</label><br>
<textarea id="about" name="about" rows="4" cols="50">
</textarea><br><br>
<input name="submit" type="submit" value="Register" />
</form>
<script src="formValidation.js" type="text/javascript"></script>
</body>
</html>
formValidation.js
function validation(){
var userID = document.registration.userid;
var userPass = document.registration.password;
var userName = document.registration.name;
var addr = document.registration.address;
var ctry = document.registration.country;
var zip = document.registration.zip;
var email = document.registration.email;
var sex = document.registration.sex;
if (userID_validate(userID,5,12)) {
if (userPass_validate(userPass,7,12)) {
if (alphabet_validate(userName)) {
if (alphanumeric_validate(addr)) {
if (empty_validate(ctry)) {
if (allnumeric_validate(zip)) {
if (emailformat_validate(email)) {
if (sex_validate(sex)) {
}
}
}
}
}
}
}
}
return false;
}
function userID_validate(userID,a,b) {
//length of string
var userID_length = userID.value.length;
if (userID_length == 0 || userID_length >= a || userID_length < b) {
alert("ID should not be empty / length should be between " + a + " to " + b + " characters");
userID.focus();
return false;
}
return true;
}
function userPass_validate(userPass,a,b) {
//length of string
var userPass_length = userPass.value.length;
if (userPass_length == 0 || userPass_length >= a || userPass_length < b) {
alert("Password should not be empty / length should be between " + a + " to " + b + " characters");
userPass.focus();
return false;
}
}
function alphabet_validate(userName) {
var betReg = /^[A-Za-z]+$/;
if (userName.value.match(betReg)) {
return true;
}
else {
alert("Username should only contain alphabet");
userName.focus();
return false;
}
}
function alphanumeric_validate(addr) {
var betnumReg = /^[0-9A-Za-z]+$/;
if (addr.value.match(betnumReg)) {
return true;
}
else {
alert("Address can only be alphanumeric");
addr.focus();
return false;
}
}
function empty_validate(ctry) {
if(ctry.value == "DEF"){
alert("Please select a country");
ctry.focus();
return false;
}
else
return true;
}
function allnumeric_validate(zip) {
var numReg = /^[0-9]+$/;
if (zip.value.match(numReg)) {
return true;
}
else {
alert("ZIP Code should only contain only numbers");
zip.focus();
return false;
}
}
function emailformat_validate(email) {
var emailReg = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(email.value.match(emailReg))
return true;
else {
alert("Please enter in a correct email address format");
email.focus();
return false;
}
}
function sex_validate(sex) {
var formValid = false;
var x = 0;
while (!formValid && x < document.getElementById("sex").length) {
if (document.getElementById("sex")[x].checked)
formValid = true;
x++;
}
if (!formValid){
alert("Please select male or female");
sex.focus();
return false;
}
else {
alert("Form successfully submitted, thank you for registering!");
window.location.reload();
return true;
}
}

Did you check the error on Console via doing Inspect Element? I copied the same code as you mentioned in Question and getting this error in Console.
Uncaught TypeError: userID is undefined
In your formValidation.js, please update the
var userID = document.registration.userid;
With correct userID as follow.
var userID = document.registration.userID;

Try putting the <script> into <head>

Related

javascript is not being called when i try to submit a form

// Staff name validation:
function staffValidation () {
var valid = true;
var staff_name = document.getElementById("staff_name").value;
var validname = /^[a-zA-Z\s]*$/;
error1 = document.getElementById("errorMsg1").innerHTML ="*";
if (staff_name == "" ) {
document.getElementById("errorMsg1").innerHTML = "*STaff name is required";
valid = false;
}
else if (full_name.match(validname)) {
valid= true;
}
else {
document.getElementById("errorMsg1").innerHTML = "* Only letters and white spaces allowed";
valid= false;
}
return valid;
}
//email validation:
function emailValidation () {
var valid = true;
var validEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = document.getElementById("email1").value;
error2 = document.getElementById("errorMsg2").innerHTML ="*";
if (email == "" ) {
document.getElementById("errorMsg2").innerHTML = "*Email is required";
valid = false;
}
else if (email.match(validEmail)) {
valid = true;
}
else {
document.getElementById("errorMsg2").innerHTML = "*Please enter a valid email.";
valid =false ;
}
return valid;
}
// Subject validation:
function subjectValidation () {
var valid = true;
var subject = document.getElementById("subject1").value;
var validname = /^[a-zA-Z\s]*$/;
error3 = document.getElementById("errorMsg3").innerHTML ="*";
if (staff_name == "" ) {
document.getElementById("errorMsg3").innerHTML = "*Subject is required";
valid = false;
}
else if (subject.match(validname)) {
valid= true;
}
else {
document.getElementById("errorMsg3").innerHTML = "* Only letters and white spaces allowed";
valid= false;
}
return valid;
}
// Problem type validation:
function problemValidation () {
var valid = true;
var prob = document.getElementsByName("problem_type")[0].value;
error4 = document.getElementById("errorMsg4").innerHTML ="*";
if (prob == "") {
document.getElementById("errorMsg4").innerHTML = "*Please select a problem type.";
valid = false;
}
else {
valid = true;
}
return valid;
}
// Description validation:
function descriptionValidation () {
var valid = true;
var description = document.getElementById("description1").value;
error5 = document.getElementById("errorMsg5").innerHTML ="*";
if (description == "" ) {
document.getElementById("errorMsg5").innerHTML = "*Description is required";
valid = false;
}
else if (description.length < 100) {
document.getElementById("errorMsg5").innerHTML = "*Please be more specific, type 100 characters minimum.";
valid = false;
}
return valid;
}
// function for form submission:
function formSubmit () {
if ( staffValidation() == false || emailValidation() == false || subjectValidation() == false || problemValidation() == false || descriptionValidation() == false ) {
document.getElementById("errorMsg").innerHTML = "* Please complete the required fields correctly";
return false;
}
else {
return true;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<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="log-it-reports2.css">
<script src="log-it-reports.js"></script>
<title>WearView Academy Homepage</title>
</head>
<body>
<div class= "content">
<div class="inner-body">
<div class="form1">
<form method="GET" onsubmit=" return formSubmit() " action="#">
<div class="error1" id= "errorMsg"></div>
<div class="error" id= "errorMsg1"></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" name="staff_name" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2"></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com">
</div><br>
<div class="error" id= "errorMsg3"></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4"></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5"></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" name="descript" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Im trying to validate a form using javascript code, however the form action automatically takes place without any validation happening. i would like to know why my javascript code is not being called which i sourced in the head tag with the name "log-it-issues.js", could it be a syntax error ? i tried to scan my code for such an error , but no result, thank you for taking time to look at my code.
The input stuff id isn't set
Give that input an id and the form will work correctly : staff_name
<input class="field" name="staff_name" id="staff_name" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name">

Why is my exception handling not catching?

This is my html code that I am trying to create the exception handling for. I am trying to create the exceptions for the first form in this code.
<form id="survey" name="survey" method="post">
<div id="errorText"></div>
<fieldset class="labelfloatleft" id="contactinfo"><legend>Your Thoughts</legend>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<label for="emailaddress">Email Address</label>
<input type="email" name="emailaddress" id="emailaddress"
size="30" placeholder="foryou#yahoo.com" />
</fieldset>
<fieldset><legend>Best Movie</legend>
<input type="radio" name="movie" id="horror" value="horror" checked="checked"/>
<label for="horror">The Horror</label>
<input type="radio" name="movie" id="badabing" value="badabing" />
<label for="badabing">Bada-Bing Bada-Boom</label>
<input type="radio" name="movie" id="roll" value="roll" />
<label for="roll">Roll or Die</label>
</fieldset>
<fieldset><legend>Comments</legend>
<label for="message">Your Opinion</label>
<textarea name="message" id="message" rows="7" cols="30"></textarea>
</fieldset>
<input type="submit" value="Send" class="button" id="submitBtn"/>
<input type="reset" value="Cancel" class="button" />
</form>
<h2>Welcome To Our World</h2>
<p class="very">We are a small time movie theater looking to help inspire
people who come to our theater. Our theaters come with
fresh food, cold and hot drinks, souvenirs and comfortable
seats to help make your experience worth while.
</p>
<h2>Most Popular</h2>
<ul>
<li>The Horror</li>
<li>Bada-Bing Bada-Boom</li>
<li>Roll or Die</li>
</ul>
<h2>Prices</h2>
<table title="prices">
<tr>
<th>Ticket</th>
<th>Price</th>
<th>Thursday Deal</th>
</tr>
<tr>
<td>Adult</td>
<td>$10.00</td>
<td rowspan="3">Half-Off</td>
</tr>
<tr>
<td>Child</td>
<td>$6.00</td>
</tr>
<tr>
<td>Senior</td>
<td>$8.00</td>
</table>
<form id="price" name="price" method="post">
<fieldset><legend>Ticket Quantity</legend>
<label for="adultinput">Adult 15-60
<input type="text" id="adultinput" value="1" size="2"/>
</label>
<label for="childinput">Child 1-14
<input type="text" id="childinput" value="0" size="2"/>
</label>
<label for="seniorinput">Senior 50 and up
<input type="text" id="seniorinput" value="0" size="2"/>
</label>
</fieldset>
<input type="submit" value="Calculate" id="calculate" class="button" />
<input type="reset" value="Cancel" class="button" />
</form>
This is my exception handling code that I am trying to get working. However, no matter how much I modify it, it never shows correctly. I have ran it in Chrome and have tried using a debugger to help however I am still unable to show the exceptions when I click the submit button.
"use strict";
var fnameComplete = true;
var lnameComplete = true;
var emailComplete = true;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
var errorDiv = document.getElementById("errorText");
function verifyFname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(fname.value)) || (fname.value === "")){
fname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
fnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyLname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(lname.value)) || (lname.value === "")){
lname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
errorDiv.style.display = "block";
lnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyEmail() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(email === "") {
email.style.background = "rgb(255,233,233)";
throw "Please enter your email.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
emailComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function validateForm(e) {
if (e.preventDefault) {
e.preventDefault(); //prevent form from submitting
} else {
e.returnValue = false; //prevent form from submitting in IE8
}
formValidity = true; //reset value for revalidation
verifyEmail();
verifyFname();
verifyLname();
if(formValidity === true) {
document.getElementsByTagName("form")[0].submit();
}
}
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
} else if(form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if(window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
It looks like you try to access a non existing field.
Here you already get the values of the fields
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
And in your comparisons you try to access a value field again. But you already have the plain value
if(!(isNaN(lname.value)) || (lname.value === "")){
}
Do it this way instead
if(!(isNaN(lname)) || (lname === "")){
}

Validation message doesn't show

Good day everyone! My problem is why the firstName & lastName error message not showing. The username & password error message is working fine. Even if the password and confirm password error is working fine. The only problem is when my firstName and lastName is empty no error message show. I already download the jQuery and include it to my head tag. I double check the id names if same with my html. I think there are same. Can somebody help me regarding to my problem? I will show you my codes below!
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
if (error_firstname = false && error_lastname = false) {
return true;
} else {
return false;
}
});
});
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>
This line is wrong:
if (error_firstname = false && error_lastname = false)
It's doing assignment, not comparison. Change that if/else to:
return !error_firstnames && !error_lastnames;
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
return !error_firstnames && !error_lastnames;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>

Doing a web site with validation form

I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>

form validation keep the information

I am trying to keep the information that you have already written even if you have an error in completing the form.Now if you have not written something correctly all the fields are cleaned and you have to start from the beginning.
This is the HTML
<form class="form" method="post" action="" name="registration" onsubmit="return formValidation()" >
<h2>Register now for free!</h2>
<label for="Fname">First name :</label>
<input type="text" name="Fname" id="Fname" placeholder="First Name">
<label for="Lname">Last name :</label>
<input type="text" name="Lname" id="Lname" placeholder="Last Name">
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="example#email.com">
<label for="password">Password :</label>
<input type="password" name="password" id="password" placeholder="******">
<label for="cpassword">Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword" placeholder="******">
<label id="gender">Gender : </label>
<input type="radio" name="sex" value="male"><span>Male</span>
<input type="radio" name="sex" value="female"><span>Female</span><br />
<input type="submit" id="submit" name="submit" value="Register">
</form>
This is the Javascript
function formValidation() {
var fName = document.getElementById("Fname").value;
var lName = document.getElementById("Lname").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var cpass = document.getElementById("cpassword").value;
if (fName_validation(fName, 20, 3)) {
if (lName_validation(lName, 20, 3)) {
if (email_validation(email)) {
if (pass_validation(pass, 20, 6)) {
}
}
}
}
function fName_validation(fName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!fName.match(check_name)) {
alert("First name should not be empty / length be between " + max + " to " + min);
fName.focus();
return false;
}
return true;
}
function lName_validation(lName, max, min) {
var check_name = /^[A-Za-z\s ]{2,20}$/;
if (!lName.match(check_name)) {
alert("Last name should not be empty / length be between " + max + " to " + min);
lName.focus();
return ;
}
return true;
}
function email_validation(email) {
var checkk_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!email.match(checkk_email)) {
alert("Please enter a valid email!");
email.focus();
return ;
}
return true;
}
function pass_validation(pass, max, min) {
var check_password = /(?=.*\d)(?=.*[a-z]).{6,}/;
if (!pass.match(check_password)) {
alert("Your password should have at least one number,one letter and should be a least 6 characters!");
pass.focus();
return false;
}
if (pass !== cpass) {
alert("Password don't match!");
cpass.focus();
return false;
}
}
alert("Well Done!You successfully registered!");
return true;
}
make sure each validation method should return true or false.
please change two return ; to return false
I would not do this with JavaScript! Because HTML5 does the job for you. Therefore there are the <input> attributes required and pattern.
<input type="text" pattern="[A-Za-z]{2,20}" required="" />
The user should be informed which pattern he can use. And everything is fine.
Example

Categories