Javascript - Executing all the validation functions on form submit - javascript

I am currently working on an Email form and have little experience with javascript but am close to accomplishing what I need but struggling at one point, spent hours trying everything I can find searching and figured someone on here would probably have my answer instantly.
I currently have 3 functions checking a box is filled, email is correct format and passwords match.
If I set each function to run on its own upon clicking submit they work perfectly for their own intended purpose, however I am having trouble working out how to make it so that all 3 functions are run upon hitting submit. My final attempt which seems closest is adding the validateForm function at the bottom of my scripts to run all scripts but this did not seem to work. Hopefully something small I am overlooking, appreciate any help.
HTML:
<form name="registerkeys" form action="form.php" method="post" onsubmit="return validateForm();">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Phone Number: <input type="text" name="phonenumber"><br>
Information on Key: <input type="text" name="keyinfo"><br>
Password: <input type="password" name="password" id="password"></label><br>
Verify Password: <input type="password" name="passwordverify" id="passwordverify"><br>
Password Hint: <input type="text" name="passwordhint"><br>
<textarea rows="5" name="message" cols="30" placeholder="Comments:"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
Javascript:
function validateFill(){
var x=document.forms["registerkeys"]["first_name"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["last_name"].value;
if (x==null || x=="") {
alert("Last name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["phonenumber"].value;
if (x==null || x=="") {
alert("Phone number must be filled out");
return false;
}
var x=document.forms["registerkeys"]["keyinfo"].value;
if (x==null || x=="") {
alert("Key info must be filled out");
return false;
}
var x=document.forms["registerkeys"]["pass1"].value;
if (x==null || x=="") {
alert("Password must be filled out");
return false;
}
var x=document.forms["registerkeys"]["passwordhint"].value;
if (x==null || x=="") {
alert("Password hint must be filled out");
return false;
}
}
function validateEmail()
{
var x=document.forms["registerkeys"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
function validatePassword(){
var password = document.getElementById("password").value;
var passwordverify = document.getElementById("passwordverify").value;
var ok = true;
if (password != passwordverify) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("passwordverify").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
function validateForm(){
var a = validateFill();
var b = validateEmail();
var c = validatePassword();
return a && b && c;
}

Your validateFill() and validateEmail() function should return true at the end.
validateFill() only returns false if validation has not passed, but never true. You should add return true at the end of the function, outside of conditions.
validateEmail() returns false if email is invalid but you are missing the return true if email is valid.
Also, to prevent duplicate popups I suggest that you change your validateForm() to something like this:
function validateForm() {
var a = validateFill();
if (a) var b = validateEmail();
else var b = false;
if (a&&b) var c = validatePassword();
else var c = false;
return a && b && c;
}
So it only checks one function until it passes, and then checks the next.

validateFill() and validateEmail() should return true at the end (right now they return nothing if validation passed.
validatePassword() should return true instead of ok.

Related

javascript validation isn't working past validating email input

When I run the following script it will not validate past the email validation. I remove the email validation and it will continue. Any insights to what may be causing the problem?
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
var atpos=vEmail.indexOf("#");
var dotpos=vEmail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
// *** check each field for SHIPPING values ***
vShipTo = document.getElementById("xShipTo").value;
if (vShipTo=="") {
document.forms['checkout_form'].elements['ship_to'].focus();
alert("No SHIP TO NAME entered");
return false;
}
Unless z is defined elsewhere, I think the error stems from z not being defined.
if (atpos<1 || dotpos<atpos+2 || dotpos+2>= (z.length) ) {
This would cause it to fail as if the two conditions are not met, the program will encounter a reference error and stop running. If z is removed, the program continues toward the end.
Edit:
Also, this code is running within a function right?
Correct this(z is undefined here)
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= z.length) {
to
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= vEmail.length) {
Here is a working snippet
checkMail();
function checkMail(){
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
var atpos=vEmail.indexOf("#");
var dotpos=vEmail.lastIndexOf(".");
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= vEmail.length) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
//return false;need to set true
}
<body>
<form name="checkout_form" id="checkout_form" action="">
Email:<br>
<input type="text" id="xEmail" name="email" value="#gmail.com">
<br>
<br><br>
<input type="submit" onclick="return checkMail();"value="Submit">
</form>
</body>
Using regular expressions is probably the best way You can use to validate email
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(String(email).toLowerCase());
}
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
if (!validateEmail(vEmail)) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
// *** check each field for SHIPPING values ***
vShipTo = document.getElementById("xShipTo").value;
if (vShipTo=="") {
document.forms['checkout_form'].elements['ship_to'].focus();
alert("No SHIP TO NAME entered");
return false;
}

Common javascript form validation not working

I've been trying to use the following javascript code to validate several fields on a contact form. The validation works for the first item being validated, the name field, but not the second, the email field. If the name field is filled in, the validation seems to skip over the email field check when it's blank and the form submits.
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
Here is the HTML on the contact form:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
Thank you
You seem to be using empty function in your if clauses which doesn't seem to be defined nor it is part of the standard javascript functions. Try getting rid of it:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
And here's a live demo.
In your code you use else if statement.
Basically what you code does is:
check name -> if that is falsy check email -> if that is falsy move into else condition.
But when the name is true, the if statement will not move to else conditions because it it already satisfied. So if you want to check both, you either separate the statements and make a 5 separate ifs, make it a switch statement or you create one long check. For example:
if ((n == null || n == "" || empty(n)) || ( ema == null || ema == "" || empty(ema) ))
{
alert("Something is missing");
return false;
}
else
{
return( true );
}
or you use multiple ifs:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
return( true );
}
The latter will always return true unless one of the if statements is triggered.
And see answer below about the empty() thing. I don't know what that is and if it messes anything up.

Remove form error with correct input

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

javascript onsubmit and 2 functions error

can someone please tell me what is going wrong?
I am trying to create a basic login page and that opens only when a correct password is written
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["myForm"]["fname2"].value;
if (x==null || x=="")
{
alert("password must be filled out");
return false;
}
}
function isValid(myNorm){
var password = myNorm.value;
if (password == "hello_me")
{
return true;
}
else
{alert('Wrong Password')
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="helloworld.html" onsubmit="return !!(validateForm()& isValid())" method="post">
Login ID: <input type="text" name="fname"> <br />
<br>
Password: <input type="password" name="fname2" > <br />
<br />
<br />
<input type="submit" value="Submit">
<input type="Reset" value="clear">
</form>
</body>
</html>
Password value is undefined in 2nd function because you are not using any params when calling isValid() function
var password = myNorm.value; //`myNorm` is undefined
to
var password = document.forms["myForm"]["fname2"].value;
See below correct function
function isValid(myNorm){
var password = document.forms["myForm"]["fname2"].value;
if (password == "hello_me"){
return true;
} else {
alert('Wrong Password')
return false;
}
}
Updated Answer on comment
if value is valid in function validateForm() then return true, see below
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["myForm"]["fname2"].value;
if (x==null || x=="")
{
alert("password must be filled out");
return false;
}
return true; // return true when input value is value
}
FIDDLE DEMO
alert for wrong password in isvalid() needs a semicolon.
The And operator is && not & in the on submit call
I am just eye balling the code
What did you observe?
You cld use ie to debug using F12 key.. Or Firefox with the suitable plugin

JavaScript double form validation

I am new to JavaScript and I have been doing a university assignment based around HTML and JavaScript. In this assignment I was asked to create a number of forms to allows a person to register for some form of educational classes. I was asked to create the form using HTML and to validate the entries using only JavaScript.
What I have been struggling to figure out is how to validate more than one form input using one block of validation (if that is possible), I want to validate both the firstname and familyname inputs using only validateForm.
Here is a segment I have been testing out:
<head>
<script>
function validateForm() {
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "") {
alert("first name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform" , action="demo_form.asp" , onsubmit="return validateForm()" , method="post">
<b>First name:</b>
<input type="text" name="firstname">
<br>
<b>Family name:</b>
<input type="text" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
Any help would be greatly appreciated!
<head>
<script>
function validateForm()
{
var firstname=document.getElementById('txtfirstname');
var familyname=document.getElementById('txtfamilyname');
if (firstname.value=="")
{
alert("first name must be filled out");
return false;
}
if (familyname.value=="")
{
alert("familyname must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform", action="demo_form.asp", onsubmit="return validateForm()", method="post">
<b>First name:</b> <input type="text" id="txtfirstname" name="firstname">
<br>
<b>Family name:</b> <input type="text" id="txtfamilyname" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
You can check all inputs, store error messages (if any) and return false at the end if there is even one failure.
i.e.
function validateForm() {
var x = document.forms["nameform"]["firstname"].value, errors = [];
if (x == null || x == "") {
errors.push("first name must be filled out");
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "") {
errors.push("family name must be filled out");
}
if(errors.length > 0) { // check if there were any errors
alert(errors.join("\n")); // alert all messages together
return false;
}
}
Couple of possibilities...
<script>
function validateForm()
{
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
alert("first name must be filled out");
return false;
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
alert("last name must be filled out");
return false;
}
return true;
}
</script>
will present an alert for each field as it fails validation and return true if all fields are OK.
<script>
function validateForm()
{
var errorString="";
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
errorString+="first name must be filled out\n";
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
errorString+="last name must be filled out\n";
}
if(errorString=="")
{
return true;
}
else
{
alert(errorString);
return false;
}
}
</script>
will return a single alert listing all of the fields that have failed validation.
In addition, I always like to use the focus() method on the first field that failed validation to put the cursor in the field that needs correcting.
Try this..
function validateForm()
{
var msg='';
var flag=false;
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "")
{
flag = true;
msg = ' First Name '
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "")
{
if(flag==true)
msg = msg + 'And Family Name '
else
msg = msg + ' Family Name ';
flag = true;
}
if (flag==true) {
msg = msg + " must be filled out";
alert(msg);
}
return false;
}
simply store it in multiple variables and have multiple if statements:
<script>
function validateForm() {
// name the variables appropriately
var firstname = document.forms["nameform"]["firstname"].value;
var familyname = document.forms["nameform"]["familyname"].value;
// check if either of them are correct, if not alert and return false.
if (firstname == null || firstname == "") {
alert("first name must be filled out");
return false;
} else if (familyname == null || familyname == ""){
alert("family name must be filled out");
return false;
}
return true;
}
</script>

Categories