admin管理员组文章数量:1406308
I'm using the jQuery Validator plugin with jQuery 1.6.2.
I'm not validating a <form>
but only a lone field by itself. This is because there are several unique <form>
's on this one page and the value from this one field is shared, copied, etc.
The success
and invalidHandler
handlers are both working correctly based on my rules.
var myValidate = function() {
$("#field").validate({
// rules, message, etc.
success: function(error){
// doing all kinds of things if this validates
return true;
},
invalidHandler: function(form, validator) {
// what to do if this fails validation
return false;
},
});
};
And I have several other functions unrelated to each other that simply call the myValidate
function above...
$('#myElement1').click(function() {
myValidate; // call to "myValidate" to validate field
// doing stuff here only if "myValidate" returns true.
});
$('#myElement2').click(function() {
myValidate; // call to "myValidate" to validate field
// only do other things here if "myValidate" returns true.
});
$('#myElement3').click(function() {
myValidate; // call to "myValidate" to validate field
// and different things to do here only if "myValidate" returns true.
});
The above is a very basic representation of what I'm doing and there are no errors.
All this is working except for one thing... my brain. I cannot seem to figure out how to stop/continue the flow of the secondary function(s) that are calling myValidate
based on the return true
or false
within myValidate
.
The way I have it, whether it returns true or false, everything still executes.
Can anyone kindly explain what I have done wrong?
I'm using the jQuery Validator plugin with jQuery 1.6.2.
I'm not validating a <form>
but only a lone field by itself. This is because there are several unique <form>
's on this one page and the value from this one field is shared, copied, etc.
The success
and invalidHandler
handlers are both working correctly based on my rules.
var myValidate = function() {
$("#field").validate({
// rules, message, etc.
success: function(error){
// doing all kinds of things if this validates
return true;
},
invalidHandler: function(form, validator) {
// what to do if this fails validation
return false;
},
});
};
And I have several other functions unrelated to each other that simply call the myValidate
function above...
$('#myElement1').click(function() {
myValidate; // call to "myValidate" to validate field
// doing stuff here only if "myValidate" returns true.
});
$('#myElement2').click(function() {
myValidate; // call to "myValidate" to validate field
// only do other things here if "myValidate" returns true.
});
$('#myElement3').click(function() {
myValidate; // call to "myValidate" to validate field
// and different things to do here only if "myValidate" returns true.
});
The above is a very basic representation of what I'm doing and there are no errors.
All this is working except for one thing... my brain. I cannot seem to figure out how to stop/continue the flow of the secondary function(s) that are calling myValidate
based on the return true
or false
within myValidate
.
The way I have it, whether it returns true or false, everything still executes.
Can anyone kindly explain what I have done wrong?
Share Improve this question edited Oct 21, 2011 at 4:41 Sparky asked Oct 19, 2011 at 1:32 SparkySparky 98.8k26 gold badges202 silver badges290 bronze badges 4- Perhaps you need to catch the event and do a preventDefault()? – Kevin McTigue Commented Oct 19, 2011 at 1:38
-
@KevinMcTigue, I'm not trying to stop the default action of an event. I'm trying to halt subsequent lines in my other functions depending on results from
myValidate
function. – Sparky Commented Oct 19, 2011 at 1:44 -
myValidate
doesn't really return anything directly it seems, it only indirectly fires callbacks, which may return something (but not to the caller ofmyValidate
). Or am I missing something? – deceze ♦ Commented Oct 19, 2011 at 2:02 - @deceze, you're not missing anything. I made a simple mistake. – Sparky Commented Oct 19, 2011 at 2:22
4 Answers
Reset to default 3I would structure your code to follow modern async patterns. Perhaps structure your code so that a call to myValidate would look like this...
$('#myElement1').click(function() {
myValidate(function(result) {
if (result === true) {
//must be valid!
} else {
//invalid
}
}
});
Here's how I would structure the myValidate function.
var myValidate = function(callback) {
$("#field").validate({
// rules, message, etc.
success: function(error){
// doing all kinds of things if this validates
return callback(true);
},
invalidHandler: function(form, validator) {
// what to do if this fails validation
return callback(false);
}
});
};
When I posted the question, I was not thinking very clearly about the whole thing at all. Besides the wrong approach, there were a couple mistakes preventing it from doing what I wanted.
Side Issue #1 - I was trying to validate this text field "on blur" so I had a whole separate event & function, which led to my unconventional approach and stupid question. All un-needed. All I needed was onkeyup
, it validates as you type out the text. No form "submit" required.
onkeyup: function(element) { this.element(element); }
Side Issue #2 - I was looking for something that was the opposite of the success:
handler, something which fires off whenever validation has failed. However, invalidHandler:
only fires when the form
is submitted. Even though I ultimately put my field inside a generic form, the form does not need a "submit" in order for validation to take place. I finally realized that the errorPlacement:
handler fires off whenever the form fails validation, exactly opposite of the success
handler... this is perfect. You don't have to "submit" anything to validate, and the text is validated as you type... it's built into the module.
Side Issue #3 - This issue was only on the SO posting and not my project. Target of validation must be a <form>
, not an <input>
field. Not only did I neglect to mention that fact, I stated the opposite. It should have been like this, $("#form").validate();
Issue #4 - And obviously, I was incorrectly creating and referencing the myValidate
function. I removed all that and just left $('#form').validate();
out by itself. Now that I have a flag being set/unset on valid/invalid Now that I'm using the .valid()
method, I can perform my other functions using a simple "if/then".
Solution:
So originally, to solve the problem, I ultimately used a flag variable with some "if/then" statements which is only what I was thinking to avoid when I posted the question... at least that's what I was thinking at the time. Maybe there's a more elegant solution...
EDIT: Yes, there is a more elegant solution...
After looking into Greg's answer, I figure out how to use the .valid()
method instead...
previous jsFiddle using a flag variable
new jsFiddle using .valid()
method as below
$("#form").validate({
onkeyup: function(element) { this.element(element); },
validClass: 'valid',
rules: {
ments: {
required: false,
maxlength: 180
}
},
success: function(error){
// stuff to do when it's valid (does not require form submit)
},
errorPlacement: function(error, element){
// stuff to do when it's not valid (does not require form submit)
}
});
And then several similar functions are attached to various other events. The "if/then" checks for the validation flag the .valid()
method before executing anything.
$('#myElement1').click(function() {
if($("#form").valid()){ // if validated
// doing stuff here only if it was already validated
};
});
$('#myElement2').click(function() {
if($("#form").valid()){ // if validated
// doing stuff here only if it was already validated
};
});
So why am I doing all this?
As stated in my original question, I am sharing the content of this one text field with several other forms on the page. They must be validated too, but this time I'm using the submitHandler:
since these other forms actually get "submitted".
This methodology allows me to to sort-of "nest" the validation of the lone field (in #form
) within the validation of the other forms being submitted (#formTWO & #formThree)...
$("#formTWO").validate({
// rules for #formTWO
submitHandler: function(form) {
copyText(); // copy text from #form into #formTWO hidden field before submission
if($("#form").valid()){ // only allow #formTWO to submit if #form is valid
form.submit();
}
}
});
$("#formThree").validate({
// rules for #formThree
submitHandler: function(form) {
copyText(); // copy text from #form into #formThree hidden field before submission
if($("#form").valid()){ // only allow #formThree to submit if #form is valid
form.submit();
}
}
});
Try restructuring your code a bit. You need to call the $().valid()
method to determine if it is valid, not from handlers inside the .validate()
options.
Also note that I couldn't get it to work without wrapping the input in a <form>
tag.
Here is my attempt at restructuring it, demonstrated in this jsFiddle:
$(function() {
// set up the validation
$("#field").validate();
// define your click handlers
$('#myElement1').click(function() {
if (myValidate()) {
alert('Click 1: Validate passed.');
} else {
alert('Click 1: Validate failed.');
}
});
$('#myElement2').click(function() {
if (myValidate()) {
alert('Click 2: Validate passed.');
} else {
alert('Click 2: Validate failed.');
}
});
$('#myElement3').click(function() {
if (myValidate()) {
alert('Click 3: Validate passed.');
} else {
alert('Click 3: Validate failed.');
}
});
});
// put your function down here
function myValidate() {
var isValid = $('#field').valid();
if (isValid) {
// doing all kinds of things if this validates
$('#feedback').text('Validation passed.');
} else {
// what to do if this fails validation
$('#feedback').text('Validation failed.');
}
return isValid;
}
Let me know if you have any questions.
myValidate;
does not call myValidate
. It merely references it.
You want an if
statement.
if (myValidate()) {
// Valid
}
if (!myValidate()) {
// Not valid
}
This is basic JavaScript (basic programming); if you aren't familiar with this, please try learning more about programming and JavaScript.
You can also pass arguments to make it work with multiple forms.
本文标签: javascriptTrying to stop function on return falseStack Overflow
版权声明:本文标题:javascript - Trying to stop function on return false - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745005713a2637248.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论