How to not submit a form if validation is false - javascript

How can I make sure the form won't submit if one of the validations is false?
$('#form').submit(function(){
validateForm1();
validateForm(document.forms['dpart2']);
validateForm(document.forms['dpart3']);
});

$('#form').submit(function(){
return (validateForm1() &&
validateForm(document.forms['dpart2']) &&
validateForm(document.forms['dpart3']))
});
Basically, you return false in the event handler function.

If the function returns false, form won't be submitted.
$('#form').submit(function(){
return validateForm1()
&& validateForm(document.forms['dpart2'])
&& validateForm(document.forms['dpart3']);
}
});

Okay, some of the other solutions will have a lazy fail... you probably want all your validation to run, so that all errors are displayed. The presumption is that your validation methods will return false if they fail.
$("#myform").submit(function() {
var ret = true;
ret = validateForm1() && ret;
ret = validateForm(document.forms['dpart2']) && ret
ret = validateForm(document.forms['dpart3'])) && ret
return ret;
});
This way all your validators will be called, but the Boolean value for any failure, will result in a fail.

If validateForm(...) and validateForm1() return a boolean (true means that no validation error occurred), then you try to do that :
$('#form').submit(function(){
if (!validateForm1() || !validateForm(document.forms['dpart2']) || !validateForm(document.forms['dpart3'])) {
return false;
}
});

A thought that comes up automatically: Even if you implemented thorough client side validation be prepared to receive any invalid request data on the server that you can possibly imagine.
Client-side validation never keeps you from server-side validation. It is just a bonus in usability.

Related

Javascript, how to check if object exists

I am making a script in Javascript script that gets a SQL response, then processes it. Basically, I want to check if the username value exists in result[1]. When it checks, it errors out and says that it does not exist. If it does not exist, I want it to return false, not stop the program.
Here is the code:
if (result[1].username != undefined) {
return true;
} else {
return false;
}
I have tried using typeof(result1) == undefined, but it gives me the same error.
First, you have to make sure the result exists, otherwise you'd be indexing into undefined which would crash your application.
Second, you can make that check less verbose with:
return (result[1] && result[1].username)
which will return a falsey value if it doesn't exist, and whatever the username is, if it does.
In case you need an explicit true to be what the function returns, you can coerce it:
return (result[1] && (result[1].username && true))
I would make sure to refactor for readability, but that's the gist.
You could use the in operator. For example:
let trueObj = { username: 'Foo' };
let falseObj = { };
if ('username' in trueObj) {
console.log('username found in trueObj');
} else {
console.log('username not found in trueObj')
}
if ('username' in falseObj) {
console.log('username found in falseObj');
} else {
console.log('username not found in falseObj')
}
First of all please check whether the result itself exists or not and make the corresponding & operator and i think this will definitely help
if (result && result[1] && result[1].username) {
return true;
} else {
return false;
}
But if you don't want to make your code complex then you can try lodash library.
https://lodash.com/

Create flash message when validation fails in KeystoneJS

I need to make flash error messages change according to the type of validation error. Right now it always says: Database error if one of my custom validations doesn't pass.
My custom validations happen in my model, and not in my controllers, so I am not sure how to traverse between the two.
Here is one of my custom validations:
User.schema.path('email').validate(function (value) {
if (validator.isEmpty(value) || validator.isEmail(value)) {
return true;
}
else {
return false;
}
});
The validation works perfectly, it's just the flash message that I want to change.
You can pass custom error messages to the validate function as well, just pair it with the function by wrapping it in an array, like this:
User.schema.path('email').validate([function (value) {
if (validator.isEmpty(value) || validator.isEmail(value)) {
return true;
}
else {
return false;
}
}, "WRONG!"]);

javaScript form validation with multiple forms

I have two forms on different pages of my website, however I want to re-use the javaScript validation. So for example:
function notnull() {
var firstName = document.forms["newsletter"]["firstName"].value;
if (firstName === null || firstName === "") {
inlineMsg('firstName', 'You must enter your name.', 3000000);
return false;
} else {
return true;
}
}
This code is only good for my newsletter form (e.g. document.forms["newsletter"]["firstName"].value) but I want to use it for my "contact" form too.
Can I build the variables up dynamically like document.forms[][].value?
You can change your notnull function to accept 2 parameters
function notnull(formType,fieldName){
var fieldName = document.forms[formType][fieldName].value;
if(fieldName === null || fieldName === "") {
inlineMsg(fieldName, 'You must enter your '+fieldName,3000000);
return false;
} else
return true;
}
something along that line. I'm unsure what your inlineMsg does. You can also alternatively pass in the error friendly name for your error message into the function.
I'm sure there are better approach of handling the above, but looking at your code only, that's what I would suggest.

Fixing a delayed callback causing false errors in jQuery Validation w/ jQuery Mobile in PhoneGap

So here's my problem.
I'm currently working on a PhoneGap application using jQuery Mobile and the Validation jQuery plugin for form validation.
I'm trying to set up a custom rule so that it will check to see if a name is already in the database, and if so, prevent the form from being submitted until the user chooses a name that is unique.
The problem is one that I've encountered before but have not yet managed to properly solve. When I call the method that executes the SQL select statement, the success callback does not get completed until after the validator has already completed and thrown false. This means that if a user enters a unique name, it will display an error, but if the user forces it to re-validate the fields, it will then be valid because the success callback had, in the meantime, completed.
Here's the relevant code:
var nameUnique;
jQuery.validator.addMethod("nameIsUnique", function(value, element) {
checkNameSQL();
return this.optional(element) || nameUnique;
}, "This name is already in use. Please choose another.");
$('#createForm').validate({
rules: {
createName: {
required: true,
nameIsUnique: true
},
createDescription: {
required: true
}
},
//snip//
});
function checkNameSQL()
{
var name = document.forms['createForm'].elements['createName'].value;
if (!(name == null || name == ""))
{
dbShell.transaction(function(tx) {
tx.executeSql("SELECT STATEMENT",[name],function(tx,results){if(results.rows.length==0){nameUnique = true;}},errorHandler)
},errorHandler);
}
}
I've simplified it where it makes sense, cutting out code not relevant to the question. As you can see, I call the method to check if the name exists, but before the success callback function triggers to set nameUnique to true, it's being returned by the validator, causing a false error.
How should I change my code to prevent this from occurring? What general programming practices should I follow to circumvent similar problems in the future? Thanks!
You can return pending as a value from the addMethod() besides true and false which can be used to delay the validation. For more info you can check the source of validation library.
Try this way:
$.validator.addMethod("nameIsUnique", function(value, element) {
var validator = this;
var previous = this.previousValue(element);
checkNameSQL(value, function(status) {
var valid = status === true;
if (valid) {
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
validator.showErrors();
} else {
var errors = {};
var message = status || validator.defaultMessage(element, "remote");
errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
validator.showErrors(errors);
}
previous.valid = valid;
validator.stopRequest(element, valid);
});
return "pending";
}, "This name is already in use. Please choose another.");
function checkNameSQL(name, callback) {
if (!(name == null || name == "")) {
dbShell.transaction(function(tx) {
tx.executeSql("SELECT STATEMENT", [name], function(tx, results) {
if (results.rows.length == 0) {
nameUnique = true;
callback(true);
}else{
callback(false);
}
}, errorHandler)
}, errorHandler);
}
}
For demo check this fiddle - http://jsfiddle.net/dhavaln/GqsVt/

How to solve client side validation problem?

I am working on a project and need to do some client side validation.
I am doing all validations by calling the onsubmit() method.
The problem that I am facing is that the validation runs just fine when I put into comments a few other statements but not otherwise.
My code:
var speak1=document.forms["form"]["speak1"].value
b = checkSpeakLanguages(speak1);
if(b==false){
return false;
}
which calls checkSpeakLanguage works properly.
But the following code works only when the above is put in comments:
var m= document.forms["form"]["maritalStatus"].value
b = checkMaritalStatus(m);
if(b==false){
return false;
}
Please help me. Please tell me why both the second part does not work when the other is present.
If the first b returns false, you return before the second part can execute. Combine the functions for your submit handler to something like:
function checkSubmit(){
var cansubmit = true,
speak1 = document.forms["form"]["speak1"].value,
m = document.forms["form"]["maritalStatus"].value;
if(!checkSpeakLanguages(speak1) || !checkMaritalStatus(m)) {
cansubmit = false;
}
return cansubmit;
}

Categories