Form validation script issues - javascript

I have two scripts at the top of a form. The first one works perfectly and provides a client-end validation for email addresses. The second one doesn't work at all, (even if I change my onsubmit to JUST that function name). I'm sure I'm missing something totally obvious. I can set it up to server-end validation, but the API with the software I'm using totally nukes the form entries, so I'm trying to avoid that.
<script>
function validateForm()
{
var x = document.forms["form5"]["element_1"].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;
}
}
</script>
<script>
function validateMisc()
{
if (document.forms["form5"]["element_27"].value !== null &&
document.forms["form5"]["element_57"].value == null)
{
alert("Misc details are required if a value is entered for Misc Projects.");
return false;
}
}
</script>
Here is my form action command currently.
<form
action="<?php echo $_SERVER["PHP_SELF"]?>"
name="form5"
action="demo_form.asp"
onsubmit="return validateForm() && validateMisc();"
method="POST">

if inputs with name="element_27" and name="element_57" exist they will never be null. They could be empty string. .value === '' and .value !== ''

Change your form like
<form action="<?php echo $_SERVER["PHP_SELF"]?>" name="form5" action="demo_form.asp" onsubmit="return validateForm();" method="POST">
Then i would revise the javascript like:
<script>
function validateForm()
{
var x=document.forms["form5"]["element_1"].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;
}
else
{
//If the email is valid, lets call the other function
validateMisc()
}
}
</script>
<script>
function validateMisc()
{
if (document.forms["form5"]["element_27"].value !== null && document.forms["form5"]["element_57"].value == null)
{
alert("Misc details are required if a value is entered for Misc Projects.");
return false;
}
}
</script>
I personally didn't check the code, so it could not work. In this case, my apologizes

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

Javascript - Executing all the validation functions on form submit

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.

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

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>

return false is not working in javascript validation

function confirmValidation() {
var confirmPass = document.getElementById('newpassword').value;
var newpass = document.getElementById('newpassword2').value;
var passLength = confirmPass.length;
if ((confirmPass == newpass) && (confirmPass != "" && newpass != "") && (passLength > 8)) {
alert("ok");
return true;
} else {
alert("no");
confirmPass.focus();
return false;
}
}
And input:
<input name="register" type="submit" class="alert_button" onclick="return confirmValidation()" value="OK" />
For the return method to work, you need to specify onSubmit attribute/listener to the form tag itself. Like so:
<form method="post" onsubmit="return confirmValidation();">
<!-- OTHER form fields -->
</form>
From w3c documentation:
The onsubmit event occurs when a form is submitted. It only applies to the FORM element.
EDIT
jsfiddle link added.
You must alter your JavaScript a little so that .focus() may fire.
function confirmValidation() {
var confirmPass = document.getElementById('newpassword');
var newpass = document.getElementById('newpassword2');
var passLength = confirmPass.value.length;
if ((confirmPass.value == newpass.value) && (confirmPass.value != "" && newpass.value != "") && (passLength > 8)) {
alert("ok");
return true;
} else {
alert("no");
confirmPass.focus();
return false;
}
}
Move your validation to the form.
document.getElementById('my_form').addEventListener('submit', confirmValidation, false);
You should use onsubmit() event in tag. Now when you submit the form, it will call the function that is written on the onsubmit() event. Only in case of Onsubmit(), it checks the return value if it's true then it proceeds further otherwise not.
<form method="post" onsubmit="return confirmValidation();">
</form>

Categories