genvalidator:检查表单验证中的复选框 [英] genvalidator: check for checkbox in form validation

查看:92
本文介绍了genvalidator:检查表单验证中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 genvalidator 测试表单中的输入字段.问题是我找不到测试复选框是否已选中的方法.这是所有字段的设置方式:

I'm using genvalidator to have some tests on input fields in a form. Problem is I can't find a way to test if a checkbox has been checked. This is how all the fields are set:

frmvalidator.addValidation("name","req","Insert your name"); 
frmvalidator.addValidation("city","req","Insert your city"); 
frmvalidator.addValidation("phone","req","Insert your phone number");

这是我的复选框

<input type="checkbox" name="agree" id="agree "value="yes"/>

我如何使它与genvalidator成为必需的?

How can I make it mandatory with genvalidator?

这是处理表单过程的部分(简而言之:如果没有错误,就可以):

This is the part that handles the form process (in short: if there aren't errors, it's ok):

if(empty($name)||empty($city)||empty($phone)||BLAHBLAH)
{
    $errors .= "\n Mandatory field. ";
}


if(empty($errors))
{
    // send the email
}

它尝试使用此JS代码没有运气:

It tried with this JS code with no luck:

function validate(form) { 

if(!document.form1.agree.checked){alert("Please check the terms and conditions");
 return false; } 


return true;
}

如果可能的话,我想使用genvalidator函数. :)

If possible I'd like to use genvalidator functions. :)

推荐答案

您正花费大量精力尝试使javascript插件正常工作.

You are expending a lot of energy trying to make the javascript plugin work.

您会考虑使用jQuery吗?如果您还没有试过,它会比听起来容易得多,而且比普通js更统一/更快速地键入.

Would you consider working with jQuery? If you haven't yet kicked its tires, it's a lot easier than it sounds -- and much more uniform / faster to type than plain js.

要使用jQuery,您只需要在文档中包括jQuery库,通常就在head标签中即可.

To use jQuery, you only need to include the jQuery library in the document, usually in the head tags thus:

<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

然后,您可以完全控制自己的工作,轻松创建自己的验证例程.

Then, you can easily create you own verification routines, with FULL control over what you are doing.

这是一个可供您学习的有效示例.如您所见,代码非常简单.

Here is a working example for you to study. As you can see, the code is pretty minimal.

单击提交"按钮(#mysub)后,我们将快速检查每个字段以查看其是否有效.如果任何字段未通过验证,我们可以将控件返回给用户,且该字段必须为彩色且焦点对准.

When the Submit button (#mysub) is clicked, we quickly check each field to see if it validates. If any field fails validation, we can return control to the user with the field colored and in focus.

如果所有字段都通过了验证,则我们在表单ID上发出submit()方法,然后它就消失了(到达action="somepage.php"属性中指定的位置).

If all fields pass validation, then we issue the submit() method on the form ID, and off it goes (to the location specified in the action="somepage.php" attribute).

请注意,我在底部添加了一些快速/肮脏的代码,以从失败的验证中删除任何CSS着色.每当字段退出时,此代码都会运行,无论该字段是否具有验证色.这不是很有效(尽管它当然不会伤害任何东西),仅用于演示可能的情况.

Note that I added some quick/dirty code at bottom to remove any css colorization from failed validations. This code runs every time a field is exited, regardless whether the field has validation coloring or not. This is not very efficient (although it certainly won't hurt anything) and is only intended to demonstrate what is possible.

嗯.我认为拥有一个具有某些属性的类,并在验证失败时添加/删除该类会更有效.好的,我非常喜欢这个想法,以至于我使用该方法创建了新的jsFiddle 看起来像.

Hmmmmm. I think it would be more efficient to have a class with certain attributes, and add/remove that class if fail validation. Okay, I liked that idea enough that I created a new jsFiddle using that method to demonstrate what that would look like.

jsFiddle此处

jsFiddle here

HTML:

<form id="fredform">
    First Name: <input id="fname" name="fname" type="text"/>
    Last Name: <input id="fname" name="fname" type="text"/>
    Email: <input id="fname" name="fname" type="text"/>
    <input id="mysub" type="button" value="Submit" />
</form>

jQuery:

arrValidate = ['fname','lname','email']

$('#mysub').click(function() {
    var nextFld, i ;
    for (i=0; i<arrValidate.length; i++){
        nextFld = arrValidate[i];
        if ( $('#'+nextFld).val() == '') {
            alert('Please complete all fields. You missed the ['  +nextFld+ '] field.');
            $('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
            $('#'+nextFld).focus();
            return false;
        }
    }

    //if it gets here, all is okay: submit!
    $('#fredform').submit();
});

//Remove any css validation coloring
$('input:not([type=button])').blur(function(){
    $(this).css({'border':'1px solid lightgrey','background':'white'});
});


请注意,还有一个看起来非常专业的jQuery验证插件.我自己没有玩过,总是喜欢编写自己的东西,但这是链接:


Note that there is also a jQuery validation plugin that looks very professional. I haven't played with it myself, always preferring to code my own stuff, but here is the link:

http://jqueryvalidation.org/documentation/

请注意非常酷的演示

所以您知道会发生什么:实现此插件比我上面建议的方法要困难得多.

Just so you know what to expect: implementing this plugin would be more difficult than the methodology I suggested above.

`      ANSWER TO YOUR COMMENT QUESTION:                                         `


关于您的评论和粘贴在粘贴框上的代码 :


Regarding your comment and the code posted at pastebin:

(很抱歉,答案很长,但是我想清楚.请仔细阅读.)

(1)请将您的javascript代码包装在document.ready函数中.我应该将其添加到我的代码示例中. 否则,代码将在DOM完全存在之前执行,并且事件触发器将不会绑定到控件(因为它们在DOM中尚不存在).因此:

(1) Please wrap your javascript code in a document.ready function. This is my fault; I should have added it to my code example. Otherwise, the code will execute before the DOM fully exists and event triggers will not be bound to the controls (because they do not yet exist in the DOM). Therefore:

arrValidate = ['checkbox']; //a global variable
$(document).ready(function() {

    $('#submit').click(function() {
        var nextFld, i ;
        for (i=0; i<arrValidate.length; i++){
            nextFld = arrValidate[i];
            if ( $('#'+nextFld).val() == '') {
                alert('Please complete all fields. You missed ['  +nextFld+ ']');
                $('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
                $('#'+nextFld).focus();
                return false;
            }
        }

        //if it gets here, all is okay: submit!
        $('#contact_form').submit();
    }); //END #submit.click

}); //END document.ready

(2)您的复选框仍然具有value="yes"属性,该属性会破坏javascript.请对此进行更改:

(2) Your checkbox still has the value="yes" attribute that breaks the javascript. Please change this:

<input type="checkbox" name="checkbox" id="checkbox" value="yes" /> <small>Ho 

对此:

<input type="checkbox" name="checkbox" id="checkbox" /> <small>Ho 

(3)您的<input value="Invia">按钮不需要type="submit" ,也不需要该控件上的name=属性.

(3) There is no need to have type="submit" for your <input value="Invia"> button, nor is there a need for a name= attribute on that control.

首先,name=属性:仅在将数据从该控件传递到处理表单的PHP(?)文件时才有用:($_SERVER['SCRIPT_NAME']). name=部分是变量名,控件的值是变量值.该按钮没有可传递的数据,因此不需要为其分配变量名.

First the name= attribute: it is only useful when passing data from that control to the PHP(?) file that processes your form: ($_SERVER['SCRIPT_NAME']). The name= part is the variable name, and the value of the control is the variable value. The button has no data to pass along, so does not need to have a variable name assigned to it.

接下来,type="submit":这不是必需的,因为您可以随时使用jQuery提交表单.在过去,在使用javascript/jQuery之前,我们有表格.那时,提交表单的唯一方法是使用type="submit"属性.没有这样的命令:$('#myFormId').submit();-但是今天有.因此,将该属性更改为type="button",然后让jQuery为您提交表单.相信我,这行得通!

Next, the type="submit": This is not required, because you can use jQuery to submit the form any time you want. In the old days, before javascript/jQuery, we had forms. Back in those days, the only way to make the form submit was to use the type="submit" attribute. There was no such command as: $('#myFormId').submit(); -- but today there is. So change that attribute to type="button" and let jQuery submit the form for you. Trust me, this works!

要考虑的另一件事:使用type="submit"后,单击该按钮时必须处理表单的默认操作.出现错误时,您不能简单地将控制权返回给用户,因为已告知表单要提交. (您必须使用event.preventDefault()覆盖默认行为-您稍后可以阅读.)

Another thing to consider: once you use type="submit" you must deal with the form's default actions when clicking that button. You cannot simply return control to the user when there is an error, because the form has been told to submit. (You must use event.preventDefault() to override the default behaviour -- you can read about that later.)

(4)必须使用其中之一来检查复选框的值方法.复选框没有值.这又是我的错,我应该在示例中写一个复选框.

(4) Checkbox values must be checked using one of these methods. Checkboxes do not have a value. This is my fault again, I should have written a checkbox into my example.

$('#submit').click(function() {
    var nextFld, i ;

    //Validate the checkbox:
    if ( $('#checkbox').is(':checked') == false ) {
        alert('You must read the informativa and check the checkbox at bottom of form');
        return false;
    }

    //Validate the rest of the fields
    for (i=0; i<arrValidate.length; i++){

(5)如果任何元素使用=submit作为其name =或id =属性,则jQuery的submit()方法将不起作用.

(5) jQuery's submit() method won't work IF any element uses =submit as either its name= or id= attribute.

这是一件奇怪的事情,但是您需要知道这一点.我刚刚(再次)在对jsFiddle示例进行故障排除时学到了它.

This is a weird thing, but you need to know it. I just learned it (again) while troubleshooting my jsFiddle example.

如果您想使用jQuery通过.submit()方法提交表单(并且我们这样做),则表单中的任何元素都不能将name=id=属性设置为提交". INPUT按钮将 name = id = 都设置为提交;这就是为什么它不起作用的原因.

If you want to use jQuery to submit your form (and we do) via the .submit() method, then no element in your form can have the name= or id= attribute set to "submit". The INPUT button had both name= and id= set to submit; that is why it wasn't working.

参考: http: //blog.sourcecoder.net/2009/10/jquery-submit-on-form-element-does-not-work/

请参阅jsFiddle中的修改后的代码示例:

See the revised code example in the jsFiddle:

此处已修改jsFiddle

Revised jsFiddle here

请,请研究上面的jsFiddle.您应该能够完全转储genvalidator插件.如果您完全了解jsFiddle,那么您将成为程序员的新地方.

这篇关于genvalidator:检查表单验证中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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