尝试在返回false时停止功能 [英] Trying to stop function on return false

查看:123
本文介绍了尝试在返回false时停止功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将jQuery Validator插件与jQuery 1.6.2一起使用.

我不是在验证<form>,而是仅验证一个单独的字段.这是因为此一页上有多个唯一的<form>,并且该字段的值被共享,复制等.

successinvalidHandler处理程序都根据我的规则正常工作.

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

我还有其他几个彼此不相关的函数,只需调用上面的myValidate函数...

$('#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.
});

上面是我正在做的事情的非常基本的表示,没有错误.

所有这一切都在起作用,除了一件事...我的大脑.我似乎无法弄清楚如何停止/继续基于myValidate中的return truefalse调用myValidate的辅助函数的流程.

我拥有它的方式,不管它返回的是true还是false,一切仍然会执行.

任何人都可以解释我做错了什么吗?

解决方案

当我发布问题时,我根本没有对整个事情进行清楚的思考.除了错误的方法外,还有一些错误使它无法执行我想要的操作.

侧面问题#1 -我试图模糊"验证此文本字段,所以我有一个单独的事件&功能,这导致了我的非常规方法和愚蠢的问题.全部不需要.我需要的只是onkeyup,它可以在您键入文本时进行验证.无需表格提交".

onkeyup: function(element) { this.element(element); }

侧面问题#2 -我正在寻找与success:处理程序相反的东西,一旦验证失败,该东西就会触发.但是,仅在提交form时触发invalidHandler:.即使最终将字段放入通用表单中,该表单也无需提交"即可进行验证.我终于意识到,只要表单验证失败,就会触发errorPlacement:处理程序,这与success处理程序完全相反……这很完美.您无需提交"任何内容即可进行验证,并且在您键入文本时,文本也会得到验证……它内置在模块中.

侧面问题3 -该问题仅在SO发布中,而不在我的项目中.验证的目标必须是<form>不是<input>字段.我不仅忽略了这一事实,而且说了相反的话.应该是这样的$("#form").validate();

问题4 -显然,我错误地创建和引用了myValidate函数.我删除了所有内容,仅将$('#form').validate();留给了自己. 现在我在有效/无效上设置/取消了一个标志现在,我正在使用.valid()方法,我可以使用简单的"if/then"来执行其他功能. >

解决方案:

因此,最初,为了解决该问题,我最终将标志变量与一些"if/then"语句一起使用,这只是我在发布问题时要避免的想法...至少这就是我的想法时间.也许有一个更优雅的解决方案...

编辑:是的,还有一个更优雅的解决方案...

研究了格雷格的答案后,我弄清楚了如何使用 .valid() 方法代替...

使用标记变量的先前jsFiddle

使用以下.valid()方法的新jsFiddle

$("#form").validate({
    onkeyup: function(element) { this.element(element); },
    validClass: 'valid',
    rules: {
        comments: {
            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)
    }
});

然后,将几个类似的函数附加到其他各种事件上. "if/then"在执行任何操作之前先检查是否有验证标志 .valid()方法.

$('#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
    };
});

那我为什么要做这一切?

正如我最初的问题所述,我正在与页面上的其他几种形式共享此文本字段的内容.它们也必须经过验证,但这次我使用的是submitHandler:,因为这些其他形式实际上是已提交"的.

这种方法使我能够在正在提交的其他表单(#formTWO和#formThree)的验证范围内,对寂寞"字段(在#form中)的验证进行嵌套" ...

$("#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();
        }
    }
});

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?

解决方案

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: {
        comments: {
            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();
        }
    }
});

这篇关于尝试在返回false时停止功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆