I have the following HTML form to take in user input:
<form method = "post" action = "email.php" onsubmit = "return validateForm()" id = "form1">
<div class = "page">
<div class = "header">
<p>
<span>CiHA Webinar Booking Form</span>
<img src = "lifespanLogo.png" class = "logo">
</p>
</div>
<div class="splitter"></div>
<div class = "body">
<div id = "wbForm">
<p>
<label>
Webinar Date
</label>
<p>
<select name = "date" id = "date">
<option value = "choose">---</option>
<option value = "Wednesday 22nd January">Wednesday 22nd January 2014</option>
<option value = "Wednesday 29th January">Wednesday 29th January 2014</option>
</select>
</p>
</p>
<p>
<label>
Name
</label>
<input name = "name" type = "text" id = "name">
</p>
<p>
<label>
Organisation
</label>
<input name = "org" type = "text" id = "org">
</p>
<p>
<label>
Email Address
</label>
<input name = "email" type = "text" id = "email">
</p>
<p id="divButtonBar">
<input type="submit" name="submit" value="Submit">
</p>
</div>
</div>
<div class="footer">
©Property Tectonics 2014
</div>
</div>
</form>
Validated by this JavaScript function which at the minute only checks to see if fields are empty or not:
<script>
function validateForm() {
if (validateDate()) {
if (validateName()) {
if (validateOrg()) {
if (validateEmail()) {
return true;
}
}
}
}
else {
return false;
}
}
function validateDate(){
var date = document.forms["form1"]["date"].value;
if (date.trim().length == 0) {
element = document.getElementById("date");
alert("Please choose a date");
element.focus();
return false;
}
else {
return true;
}
}
function validateName(){
var name = document.forms["form1"]["name"].value;
if (name.trim().length == 0) {
element = document.getElementById("name");
alert("Please enter your name");
element.focus();
return false;
}
else {
return true;
}
}
function validateOrg(){
var org = document.forms["form1"]["org"].value;
if (org.trim().length == 0) {
element = document.getElementById("org");
alert("Please enter your organisation");
element.focus();
return false;
}
else {
return true;
}
}
function validateEmail(){
var email = document.forms["form1"]["email"].value;
if (email.trim().length == 0) {
element = document.getElementById("email");
alert("Please enter your email address");
element.focus();
return false;
}
else {
return true;
}
}
</script>
Yet when I purposely leave fields blank the form still submits and progresses to email.php. Any help here? I just can't see the issue.
Thanks
This code:
function validateForm() {
if (validateDate()) {
if (validateName()) {
if (validateOrg()) {
if (validateEmail()) {
return true;
}
}
}
}
else {
return false;
}
}
will only ever return false if validateDate() is false.
Instead try something like:
function validateForm() {
if (validateDate() && validateName() && validateOrg() && validateEmail() ) {
return true;
}
else {
return false;
}
}
You don't have else clauses for many of your if statements:
function validateForm() {
if (validateDate()) {
if (validateName()) {
if (validateOrg()) {
if (validateEmail()) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
else {
return false;
}
}
Or you could write it more simply as:
function validateForm() {
if (validateDate() && validateName() && validateOrg() && validateEmail()) {
return true;
}
else {
return false;
}
}
Or even as:
function validateForm() {
return (validateDate() && validateName() && validateOrg() && validateEmail());
}
if you're comfortable adding jQuery to this, you could use
$("#form1").submit(function(e) {
e.preventDefault();
if(validateForm()) {
// submit the form
}
});
see the example fiddle with jquery support: http://jsfiddle.net/2BmY8/
There is no else { return false; } condition for the validateName(), validateOrg() or validateEmail() structures. They don't explicitly return false, instead they do nothing (which is enough for the form to submit).
Related
I want the form to not be submitted when the inputs are wrong. The error messages do appear but my form still gets submitted nonetheless. I cant seem to find the problem would appreciate the help thank you :)-----------------------------------------------------------------------------------------------------
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading" >First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
fname.style.color="red";
return false;
} else {
fname.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false)
{
errorC.innerHTML = "Wrong format";
mcode.style.color="red";
return false;
} else {
mcode.innerHTML = "";
}
return true; }
The problem seems to be these four lines of code:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
fname and mname are strings, therfore fname.style and mname.style both result in undefined. Obviously you can't set properties on undefined which is why you are getting an error.
//You are getting the value properties which are strings:
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
The error is stopping your code before you can return false, preventing the cancelation of the form submit.
The solution is to instead make two more variables storing the actual input elements:
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
Then change lines:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
to:
finput.style.color="red";
finput.innerHTML = "";
minput.style.color="red";
minput.innerHTML = "";
Here is a working version:
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading">First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
finput.style.color = "red";
return false;
} else {
finput.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false) {
errorC.innerHTML = "Wrong format";
minput.style.color = "red";
return false;
} else {
minput.innerHTML = "";
}
return true;
}
</script>
Pass the event to the form validation function
onsubmit="return validateForm(e)"
Then prevent default submission using
e.preventDefault();
Your return statement should be inside a condition. Right now you're existing the condition and ending the function with a return true; regardless of what the conditional statements have already returned. So:
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}else{
return true; // THIS IS WHERE YOU NEED TO RETURN TRUE
}
I see you're returning false in multiple if statements. You'll need to find a way to unify the conditions so that you have one return only for for either true or false.
My school gave me a week to learn JavaScript. We started with form validation.
I was able to successfully figure out name and email address but I am unable to add the date validation that is required.
My code so far:
function formValidator() {
// Make quick references to our fields
var name = document.getElementById('name');
var email = document.getElementById('email');
// Check each input in the order that it appears in the form!
if (isAlphabet(name, "Please enter only letters for your name")) {
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;
}
}
//javascriptkit.com/script/script2/validatedate.shtml
function checkdate(input) {
var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval = false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else { //Detailed check for valid date ranges
var monthfield = input.value.split("/")[0]
var dayfield = input.value.split("/")[1]
var yearfield = input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield - 1, dayfield)
if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval = true
}
if (returnval == false) input.select()
return returnval
}
<div id="form">
<h1>Questions? Contact Us!</h1>
<form onsubmit='return formValidator()'>
<label for="name">Name:</label>
<input type='text' id='name' /><br />
<label for="email">Email:</label>
<input type='text' id='email' /><br />
<label for="date">Date: </label>
<input type="text" id="date" required /> <br>
<label for="message">Question:</label>
<textarea name="message" rows="8" cols="20" required>Please make sure your question is at least five words.</textarea> <br>
<input type='submit' value='Check Form' />
</form>
</div>
I think I should change the function check date but I'm not sure what to do.
Thanks.
Wire up the date validation in your function.formValidator - I modified that function to use an isValid to avoid large numbers of nested validation.
IF you want to ONLY work with one at a time, starting with name you could use that in the next as well by adding it to the start of each one, it skips if it is false:
if (isValid && !emailValidator(email, "Please enter a valid email address"))
Note the added ! on !emailValidator says to make isValid false if it fails.
function formValidator() {
// Make quick references to our fields
var name = document.getElementById('name');
var email = document.getElementById('email');
var mydate = document.getElementById('date'); // add this one
var isValid = true; //added this (form level valid true/false)
// Check each input in the order that it appears in the form!
if (!isAlphabet(name, "Please enter only letters for your name")) {
isValid = false;
}
if (!emailValidator(email, "Please enter a valid email address")) {
isValid = false;
}
// check the date
if (!checkdate(mydate)) {
isValid = false;
alert("bad date " + mydate.value);
}
return isValid;
}
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;
}
}
//javascriptkit.com/script/script2/validatedate.shtml
function checkdate(input) {
var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval = false;
if (!validformat.test(input.value)) {
alert("Invalid Date Format. Please correct and submit again.");
} else { //Detailed check for valid date ranges
var monthfield = input.value.split("/")[0];
var dayfield = input.value.split("/")[1];
var yearfield = input.value.split("/")[2];
var dayobj = new Date(yearfield, monthfield - 1, dayfield);
if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.");
} else {
returnval = true;
}
}
if (returnval == false) {
input.select();
}
return returnval;
}
<div id="form">
<h1>Questions? Contact Us!</h1>
<form onsubmit='return formValidator()'>
<label for="name">Name:</label>
<input type='text' id='name' /><br />
<label for="email">Email:</label>
<input type='text' id='email' /><br />
<label for="date">Date: </label>
<input type="text" id="date" required /> <br>
<label for="message">Question:</label>
<textarea name="message" rows="8" cols="20" required>Please make sure your question is at least five words.</textarea> <br>
<input type='submit' value='Check Form' />
</form>
</div>
I'm having trouble with my form validation logic in my year one Javascript project.
Specifically with my errors reporting with the events.
The page randomly refreshes when I'm testing for "no username entered" etc.
Some errors will display for a moment and disappear.
Any help would be much appreciated, and will contribute to fixing the overall problem.
<body onload="setup()">
<div class="container-fluid">
<div class="page-header" class = "row">
<div class="col-lg-12">
<img id="banner" src = "pictures/homepage/banner.jpg" width = "100%" height = "20%"></img>
</div>
<p id="charc">Charcoal</p>
</div>
<div class="butts">
<button onclick="dropdown()" class="button">Categories</button>
<button class="button">My Account</button>
<button class="button">Shopping Cart</button>
<button id="loggedIn-Out" class="button">Login/Register</button>
</div>
<div id="myDropDwn" class= "dropContent">
womens
mens
shoes
accessories
</div>
</div>
<div class="login-page" class="col-lg-6">
<div class="form">
<form id="logForm" class="login-form">
<input id="username" type="text" placeholder="Username">
<div id="login-user-error" class="errorReps"></div>
<input id="password" type="password" placeholder="Password">
<div id="login-pass-error" class="errorReps"></div>
<button onclick="loginUser()">Login</button>
<div id="login-error" class="errorReps"></div>
<p class="loginMessage"> Not Registered? Register
<br>
<br>
Logout
</form>
<form id="regForm" class="register-form">
<input id="newFName" type="text" placeholder="First Name">
<div id="reg-FName-error" class="errorReps"></div>
<input id="newLName" type="text" placeholder="Last Name">
<div id="reg-LName-error" class="errorReps"></div>
<input id="newUName" type="text" placeholder="Username">
<div id="reg-UName-error" class="errorReps"></div>
<input id="newPass" type="password" placeholder="Password">
<div id="reg-pass-error" class="errorReps"></div>
<div id="passStrength"></div>
<input id="newEmail" type="email" placeholder="Email">
<div id="reg-email-error" class="errorReps"></div>
<input id="newPhone" type="number" placeholder="Tel. Number">
<div id="reg-phone-error" class="errorReps"></div>
<button onclick="registerUser()">Create</button>
<p class="loginMessage"> Already Registered? Login
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$('.loginMessage a').click(function(){
$('form').animate({height:"toggle", opacity: "toggle"}, "slow");
});
</script>
<script>
// pre-coded users
var existingUsers =
[
{
firstname: "Gerry",
lastname: "Agnew",
username: "GerryA",
password: "password123",
email: "gerry#gmit.ie",
phone:"0833333333"
},
{
firstname: "Sean",
lastname: "Duignan",
username: "SeanD",
password: "password456",
email: "sean#gmit.ie",
phone:"0822222222"
},
{
firstname: "Michael",
lastname: "Duignan",
username: "MichaelD",
password: "password789",
email: "michael#gmit.ie",
phone:"0844444444"
}
]
//function setup()
//{
// setup functions
//}
function dropdown()
{
document.getElementById("myDropDwn").classList.toggle("show");
}
username.addEventListener('blur', logUserVerify, true);
password.addEventListener('blur', logPassVerify, true);
newFName.addEventListener('blur', fNameVerify, true);
newLName.addEventListener('blur', lNameVerify, true);
newUName.addEventListener('blur', regUserVerify, true);
newPass.addEventListener('blur', regPassVerify, true);
newEmail.addEventListener('blur', emailVerify, true);
newPhone.addEventListener('blur', phoneVerify, true);
function loginValidate()
{
if(username == "")
{
document.getElementById("login-user-error").innerHTML = "Username required";
//username.focus();
return false;
}
if(password == "")
{
document.getElementById("login-pass-error").innerHTML = "Password required";
password.focus();
return false;
}
}
function registerValidate()
{
if(registerFName == "")
{
document.getElementById("reg-FName-error").innerHTML = "First Name required";
newFName.focus();
return false;
}
if(registerLName == "")
{
document.getElementById("reg-LName-error").innerHTML = "Last Name required";
newLName.focus();
return false;
}
if(registerUName == "")
{
document.getElementById("reg-UName-error").innerHTML = "Username required";
newUName.focus();
return false;
}
if(registerUName.length < 8)
{
document.getElementById("reg-UName-error").innerHTML = "Username must be 8 characters or more";
newUName.focus();
return false;
}
if(registerPass == "")
{
document.getElementById("reg-pass-error").innerHTML = "Password required";
newPass.focus();
return false;
}
if(registerEmail == "")
{
document.getElementById("reg-email-error").innerHTML = "Email required";
newEmail.focus();
return false;
}
if(registerPhone == "")
{
document.getElementById("reg-phone-error").innerHTML = "Phone number required";
newPhone.focus();
return false;
}
}
// Event Functions
function logUserVerify()
{
if (username != "")
{
document.getElementById("login-user-error").innerHTML = "";
return true;
}
}
function logPassVerify()
{
if (password != "")
{
document.getElementById("login-pass-error").innerHTML = "";
return true;
}
}
function fNameVerify()
{
if (registerFName != "")
{
document.getElementById("login-FName-error").innerHTML = "";
return true;
}
}
function lNameVerify()
{
if (registerLName != "")
{
document.getElementById("login-LName-error").innerHTML = "";
return true;
}
}
function regUserVerify()
{
if (registerUName != "")
{
document.getElementById("login-UName-error").innerHTML = "";
return true;
}
if (registerUName > 8)
{
document.getElementById("login-UName-error").innerHTML = "";
return true;
}
}
function regPassVerify()
{
if (registerPass != "")
{
document.getElementById("login-pass-error").innerHTML = "";
return true;
}
}
function phoneVerify()
{
if (registerPhone != "")
{
document.getElementById("login-phone-error").innerHTML = "";
return true;
}
}
function emailVerify()
{
if (registerEmail != "")
{
document.getElementById("login-email-error").innerHTML = "";
return true;
}
}
// Login/Register Functions
function loginUser()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for (i = 0; i < existingUsers.length; i++)
{
if(username == existingUsers[i].username && password == existingUsers[i].password)
{
alert(username + " Is logged in");
document.getElementById("loggedIn-Out").innerHTML = username;
document.getElementById("login-user-error").innerHTML = "";
localStorage.user = username;
localStorage.pass = password;
return;
}
else if(username != existingUsers[i].username)
{
document.getElementById("login-user-error").innerHTML = "Invalid, user does not exist";
username.focus();
return false;
}
else
{
loginValidate();
}
}
}
function logoutUser()
{
localStorage.removeItem("user");
localStorage.removeItem("pass");
document.getElementById("loggedIn-Out").innerHTML = "Login/Register";
}
function registerUser()
{
var registerFName = document.getElementById("newFName").value;
var registerLName = document.getElementById("newLName").value;
var registerUName = document.getElementById("newUName").value;
var registerPass = document.getElementById("newPass").value;
var registerEmail = document.getElementById("newEmail").value;
var registerPhone = document.getElementById("newPhone").value;
localStorage.regFname = registerFName;
localStorage.regLname = registerLName;
localStorage.regUname = registerUName;
localStorage.regPass = registerPass;
localStorage.regMail = registerEmail;
localStorage.regPhone = registerPhone;
var newUser =
{
firstname: registerFName,
lastname: registerLName,
username: registerUName,
password: registerPass,
email: registerEmail,
phone: registerPhone
}
for(i = 0; i < existingUsers.length; i++)
{
if(registerUName == existingUsers[i].username)
{
document.getElementById("reg-UName-error").innerHTML = "Username already exists";
newUName.focus();
return false;
}
if(registerEmail == existingUsers[i].email)
{
document.getElementById("reg-email-error").innerHTML = "Email already exists";
newEmail.focus();
return false;
}
registerValidate();
}
existingUsers.push(newUser);
}
// Password Strength functions
function passwordStr()
{
var passValue = document.getElementById("newPass").value;
if(passValue.length >= 8 && passValue.length <= 10)
{
document.getElementById("passStrength").innerHTML = "Weak";
}
else if(passValue.length > 10 && passValue.length <= 16)
{
document.getElementById("passStrength").innerHTML = "Average";
document.getElementById("passStrength").style.color = "yellow";
}
else if(passValue.length > 16)
{
document.getElementById("passStrength").innerHTML = "Strong";
document.getElementById("passStrength").style.color = "green";
}
else
{
document.getElementById("passStrength").style.color = "red";
}
}
var passInput = document.getElementById("newPass");
passInput.addEventListener("input", passwordStr);
</script>
Add a type attribute to your login button. type="button"
<button type="button" onclick="loginUser()">Login</button>
Without specifying a type, the button will default to submit behavior. You seem to be handling the login without default form submission, so setting the type to button just changes it to a regular button hence no form submission.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am working on a form but my form is not working whenever I press submit. I am trying to evaluate whether sections of the form is empty, the email, and the number of digits for a user id. When I press submit nothing happens and I have been stuck like this for a while. FYI I have to use plain js and html.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Student Login Form</title>
<link rel='stylesheet' href='studentform.css' type='text/css' />
<script src="studentform.js"></script>
</head>
<body onload="document.form.studentid.focus();">
<h1>Student Login</h1>
<div class="container">
<form name="form" onsubmit="return validate();">
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
`
Js.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(nameEmpty(name))
{
if(studentidEmpty(studentid))
{
if(emailEmpty(email))
{
if(digitCheck(studentid))
{
if checkEmail(email)
{
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid){
if ( studentid == "" ){
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name){
if ( name == "" ){
alert("Please provide your name!");
name.focus() ;
return false;
}
}
function emailEmpty(email){
if( email == "" ){
alert( "Please provide your email!" );
email.focus();
return false;
}
function digitCheck(studentid){
var ok = studentid.search(".{8,}");
if (ok!=0){
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid){
var personList = [["Joe",11111111],["Tammy",22222222],["Jones",33333333]];
for (list in personList) {
if (name in list && studentid in list){
alert("Welcome! An email verification with be sent soon.");
return true;
} else{
alert("Student Name and/or ID not found in records");
return false;
}
}
}
}
I think you should fix this line:
if checkEmail(email)
to
if (checkEmail(email))
you have forgotten the parentheses.
Edit:
I have completely fixed your code. Your errors:
you have forgotten to add else clauses for your field checkers, they were only returning false if the validation failed
your checking "if array contains value" was wrong, I have added a method from here
you were trying to focus on the values, not tags
you were trying to test email value from the "value of the value" not "value"
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
return verify(name, studentid);
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
document.getElementById("studentid").focus();
return false;
} else {
return true;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
document.getElementById("name").focus();
return false;
} else {
return true;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
document.getElementById("email").focus();
return false;
} else {
return true;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
} else {
return true;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
return false;
} else {
return true;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (contains.call(list, name) && contains.call(list, studentid)) {
alert("Welcome! An email verification with be sent soon.");
return true;
}
}
alert("Student Name and/or ID not found in records");
return false;
}
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
<div>
<form>
<label for="name">Name:</label>
<input type="text" name="name" size="50" id="name" required />
<label for="studentid">Student ID:</label>
<input type="number" name="studentid" maxlength="8" id="studentid" required />
<label for="email">Email:</label>
<input type="email" name="email" size="50" id="email" required />
<label for="emailconfirm">Email Confirmation:</label>
<input type="checkbox" name="emailconfirm" checked /><span>Send an email confirmation</span>
<select>
<option selected>Student Registration</option>
<option>Transcript</option>
</select>
<input onclick="return validate();" type="submit" name="submit" value="Submit" />
</form>
</div>
Validate function always return false !! It shouldn't.
function validate(){
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
return nameEmpty(name) && studentidEmpty(studentid) && emailEmpty(email) && digitCheck(studentid) && checkEmail(email) && verify(name, studentid);
}
Then be sure your form looks like :
<form name="form" onsubmit="return validate();" action="javascript:void(0)">
</form>
And your autofocus input to look like :
<input type="number" name="studentid" maxlength="8" id="studentid" required autofocus/>
You're forgetting the parentheses.
It is also wrong to start and end each function, try using the code below with these corrections.
function validate() {
var studentid = document.getElementById("studentid").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (nameEmpty(name)) {
if (studentidEmpty(studentid)) {
if (emailEmpty(email)) {
if (digitCheck(studentid)) {
if (checkEmail(email)) {
verify(name, studentid)
}
}
}
}
}
return false;
}
function studentidEmpty(studentid) {
if (studentid == "") {
alert("Please provide your student id!");
studentid.focus();
return false;
}
}
function nameEmpty(name) {
if (name == "") {
alert("Please provide your name!");
name.focus();
return false;
}
}
function emailEmpty(email) {
if (email == "") {
alert("Please provide your email!");
email.focus();
return false;
}
}
function digitCheck(studentid) {
var ok = studentid.search(".{8,}");
if (ok != 0) {
alert("Please provide ID with 8 digits.");
return false;
}
}
function checkEmail(email) {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
function verify(name, studentid) {
var personList = [
["Joe", 11111111],
["Tammy", 22222222],
["Jones", 33333333]
];
for (list in personList) {
if (name in list && studentid in list) {
alert("Welcome! An email verification with be sent soon.");
return true;
} else {
alert("Student Name and/or ID not found in records");
return false;
}
}
}
I have the following form:
<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT TYPE = 'Radio' Name ='q1' value= 'a'>
Usually<INPUT TYPE = 'Radio' Name ='q1' value= 'b'>
Rarely<INPUT TYPE = 'Radio' Name ='q1' value= 'c'>
Never<INPUT TYPE = 'Radio' Name ='q1' value= 'd'>
<input type="submit" value="addData" />
</form>
I am trying to validate whether a Radio button has been selected.
The code I am using:
<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
This is not working. Any ideas?
When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:
<script type="text/javascript">
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
function validateForm()
{
if(validateRadio (document.forms["survey1"]["q1"]))
{
return true;
}
else
{
alert('Please answer all questions');
return false;
}
}
</script>
Regards
My solution for validation complex forms include radios.
Usage is simple, function return TRUE/FALSE after validation.
var rs_target is ID of form
scTo is my custom func to scroll to ID, you can use own function to show/scroll errors
scTo("#"+err_target);
Error box will be like
<div class="rq_message_box rq_message_box_firstname display-none">err message</div>
Validation
var validation = validateForm(rs_target);
if(validation == false){
return false;
}
Function
function validateForm(rs_target) {
var radio_arr = [];
var my_form = $("#"+rs_target);
my_form = my_form[0];
$(".rq_message_box").hide(); //clear all errors
//console.log(my_form);
var err = false;
var err_target = "";
for (key in my_form) {
//console.log("do");
if(!my_form[key]||my_form[key]==null||err){
break;
}
//console.log(my_form[key].name);
var x = my_form[key].value;
//console.log(x);
if(my_form[key].type == "radio"){
//console.log("radio");
if(radio_arr[my_form[key].name] != true){
radio_arr[my_form[key].name] = null;
}
if(my_form[key].checked){
radio_arr[my_form[key].name] = true;
}
}else{
if (x == null || x == "") {
//console.log(form[key].name.toString() + " must be filled out");
err = true;
err_target = my_form[key].name;
//return false;
}
}
}
//console.log(radio_arr);
var rad_err = false;
for (key in radio_arr) {
if(rad_err){
break;
}
var x = radio_arr[key];
if (x == null || x == "") {
//console.log("RADIO> "+key + " must be filled out");
rad_err = true;
err_target = key;
}
}
if(err || rad_err){
// some error stuff, for me show prepared error/help box with class [".rq_message_box_"+err_target] / err_target is name of input like [.rq_message_box_firsname]
$(".rq_message_box_"+err_target).show(); //show error message for input
scTo("#"+err_target); //scroll to - custom func
return false;
}else{
return true;
}
}