Prevent form from being submitted and preserve data using Javascript onsubmit - javascript

So I have my form setup like this:
<form id="form" name='form' method="post" action="#" onsubmit="validate(this)">
and I have the following function to validate the form, but the problem is, when the validation fails, the form gets reset and thus you have to retype all the information. Although from what I've read having return false; in the validation function should prevent this, so what am I doing wrong?
var error = false;
var errors = [];
function validate(form)
{
var name = form.inputname.value;
var phone = form.inputphone.value;
var email = form.inputemail.value;
var make = form.inputmake.value;
var model = form.inputmodel.value;
var month = form.month.value;
var day = form.day.value;
if(!name || !phone || !email || !make || !model || !day || !month)
{
alert("Please complete the form");
errors[errors.length] = "Incomplete Form\n";
return false;
}
if (month < 1 || month > 12 || day < 1 || day > 30) {
alert("Please enter valid Month/Day in format 1-12/1-30 ");
document.getElementById("month").focus();
errors[errors.length] = "Invalid Date\n";
return false;
}
if (errors.length > 0) {
alert(errors);
return false;
}
else if (errors.length == 0)
{
window.location.href("reserved300771292.aspx");
}
return true;
}
Thanks in advance!!

Firstly although your function is correctly returning true or false depending on your requirement, you are not returning it to the onsubmit, so your form onsubmit should read
onsubmit="return validate(this)"
secondly you may experience an interesting bug due to the errors[] being global. If the first form validation fails, then every subsequent form submit will fail also (even if it is valid) as you are not clearing the errors array. Declare the errors[] variable inside the validate function.
Also I'm not sure the exact behavior you will get tring to redirect the browser in the validate function. This may stop the form from submitting (i.e. the data collected on the form will not be posted) or the redirect will not work. Personally I wouldn't try this approach, redirect on the server side if everything works the way it should, as it is best practice to validate server side and client side

Related

JavaScript form validation with else if

I have been creating JavaScript validation for a form though run into difficulties. There are currently two parts to parts at (at the moment) for JavaSCript to check (email and sms). THe script is only running email and not checking sms at all when should be checking both together. If both are fine then return true. Any ideas?
function validateForm() {
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
var errordiv = document.getElementById('error');
var errorsms = document.getElementById('errorsms');
/*postOptOutSix.checked = false;
postOptOutForever.checked = false*/
// Conditions
if (document.getElementById("emailradios") ==null && document.getElementById("emailforever") ==null) {
if (document.getElementById("smsforever") ==null && document.getElementById("smsforever") ==null) {
return true;
}
else if (document.getElementById("checksms").checked ==false && document.getElementById("smsOptOutSix").checked ==false && document.getElementById("smsOptOutForever").checked ==false) {
errordiv.innerHTML += "<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
else if (document.getElementById("checkemail").checked ==false && document.getElementById("emailOptOutSix").checked ==false && document.getElementById("emailOptOutForever").checked ==false) {
errorsms.innerHTML += "<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'";
return false;
} else {
return true;
}
}
You'd need to separate the 2 conditions checks, and only then check if some failed or not before returning.
Something like this should do the trick:
function validateForm () {
var errors = [];
// Empty any previous errors
document.getElementById('error').innerHTML = "";
// Check for SMS
if (!document.getElementById("checksms").checked &&
!document.getElementById("smsOptOutSix").checked &&
!document.getElementById("smsOptOutForever").checked) {
// add the SMS error to the array
errors.push("<p id='errorp' style='color:red;'>*SMS - Please either opt-in post or select either of the options.'");
}
// Check for Email
if (!document.getElementById("checkemail").checked &&
!document.getElementById("emailOptOutSix").checked &&
!document.getElementById("emailOptOutForever").checked) {
// add the Email error to the array
errors.push("<p id='errorp' style='color:red;'>*Email - Please either opt-in post or select either of the options.'");
}
// Display the error(s) if any
if (errors.length > 0) {
errors.forEach(function (err) {
document.getElementById('error').innerHTML += err;
});
return false;
}
return true;
}
Also, I noticed that id='errorp' is there twice. Rename one of them.
var emailBoxChecked = document.getElementById("checkemail").checked
var emailBoxChecked = document.getElementById("checksms").checked
You are setting the same variable from different elements. Shouldn't it be like this?
var emailBoxChecked = document.getElementById("checkemail").checked
var smsBoxChecked = document.getElementById("checksms").checked
Use HTML required and pattern attributes along with inputElement.checkValidity() which returns true or false. You could look on keyup, for example, to make sure all inputs are valid and if so enable the submit button and if not disable it.

Validate forms using javascript

I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

Form submits despite of javascript validation returning false and displaying alert message

I have a form to be filled in by the users, and empty fields would prompt JavaScript validation to return a message to fill in that specific field. I'm able to accomplish this all except that in spite of returning an "Alert" message, the form gets submitted. How do I avoid this? Here's my JavaScript:
function validateHandAppr(theForm) {
// Recom or Not Recom
if (document.project.rec.selectedIndex == 0) {
alert("Please Choose the Recommendation Priority .");
project.rec.focus();
return false;
}
// Recommended priorities
if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value == "") {
alert("Fill in the date when culture was received.");
project.recvd_dt.focus();
return false;
}
if (document.project.rec.selectedIndex == 2 && document.project.recvd_by.value == "") {
alert("Specify who received the culture.");
project.recvd_by.focus();
return false;
}
if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value != "") {
var validformat = /^\d{4}\-\d{2}\-\d{2}$/; //.test(project.recvd_dt.value) //Basic check for format validity
if (!validformat.test(project.recvd_dt.value)) {
alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
return false;
} else { //Detailed check for valid date ranges
var yearfield = project.recvd_dt.value.split("-")[0]
var monthfield = project.recvd_dt.value.split("-")[1]
var dayfield = project.recvd_dt.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.")
return false;
} else {
return true;
}
}
}
}
Following is the form where JavaScript is being called:
<form accept-charset="UTF-8" id="project" name="project"
action="hand_submit_forms.php" method="post"
onSubmit="return validateHandAppr(this)"
class="user-info-from-cookie" enctype="multipart/form-data">
Following is the updated code,as per suggested by DaveRandom:
function validateHandAppr(theForm) {
// Recom or Not Recom
//var val=true;
if ( document.project.rec.selectedIndex == 0 )
{
alert ( "Please Choose the Recommendation Priority ." );
document.project.rec.focus();
return false;
}
// Recommended priorities
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value == "")
{
alert("Fill in the date when culture was received.");
document.project.recvd_dt.focus();
return false;
}
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_by.value == "")
{
alert("Specify who received the culture.");
document.project.recvd_by.focus();
return false;
}
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value != ""){
var validformat=/^\d{4}\-\d{2}\-\d{2}$/ ; //.test(project.recvd_dt.value) //Basic check for format validity
if (!validformat.test(project.recvd_dt.value))
{
alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
return false;
}
else{ //Detailed check for valid date ranges
var yearfield=project.recvd_dt.value.split("-")[0]
var monthfield=project.recvd_dt.value.split("-")[1]
var dayfield=project.recvd_dt.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.")
return false;}
else
{
return true; }
}
}
// return val;
}
The problem is these lines:
project.rec.focus();
// ...
project.recvd_dt.focus();
// ...
project.recvd_by.focus();
Your validation conditions reference document.project but the above lines represent simply project - which does not exist globally because it is a child of document, not window and you did not declare it locally.
Because these lines are between the alert() lines and the return false; lines, you will see the alert but the return statement will never be reached - so the function will not return false and the form will be submitted.
If you change the lines to:
document.project.rec.focus();
// ...
document.project.recvd_dt.focus();
// ...
document.project.recvd_by.focus();
...it should work.
However
You should assign the functions to the <form>s DOM object's submit event instead of using inline event handlers.
If you do this, you will be passed an event object to the first argument of the function, and you can use event.preventDefault() instead of returning false. This would avoid the problem (if the line was placed before the error occurred), and is generally a better way to handle this, because returning false also stops propagation of the event, which may not be desired - actually this makes little difference in this specific case but as a general rule it is true.
If you do this, the handler will be executed in the context of the DOM object - so the this variable will be a reference to it, and you won't need to pass it in as an argument.

Use jQuery.post() result in javascript function

I've got no clue how to do the following, so I wasn't sure what to search for either.
For validating my registration form I've a javascript function that checkes the existence of the inserted username in the database onblur of the username textfield.
function checkUsername(username){
$.post("checkmail.php", {username: username} , function(data){
var $response=$(data);
var response = $response.filter('#username-response').text();
if(response == "taken") {
document.getElementById('username').style.borderColor = rood;
valid = false;
}
});
}
This works fine, but now I want to validate it again onsubmit of the form in case users decide to submit an existing username.
function validateForm() {
var valid = true;
//checks different fields
//now check voor username existence
var username = document.getElementById('username').value;
checkUsername.call(username);
if (!valid) {
return false;
}
else {
return true;
}
}
I'm not familiar enough with Javascript to get this working. Probably thinking in the wrong direction...
You can use synchronous ajax call for this as you are using return data for validation.

Categories

Resources