简体   繁体   English

genvalidator:检查表单验证中的复选框

[英]genvalidator: check for checkbox in form validation

I'm using genvalidator to have some tests on input fields in a form. 我正在使用genvalidator对表单中的输入字段进行一些测试。 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");

This is my checkbox 这是我的复选框

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

How can I make it mandatory with genvalidator? 如何通过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
}

It tried with this JS code with no luck: 它尝试了以下JS代码,但没有运气:

function validate(form) { 

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


return true;
}

If possible I'd like to use genvalidator functions. 如果可能的话,我想使用genvalidator函数。 :) :)

You are expending a lot of energy trying to make the javascript plugin work. 您正花费大量精力尝试使javascript插件正常工作。

Would you consider working with jQuery? 您是否考虑使用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. 如果您还没有试过,它会比听起来容易得多,而且比纯js更统一/更快速地键入。

To use jQuery, you only need to include the jQuery library in the document, usually in the head tags thus: 要使用jQuery,您只需要在文档中包括jQuery库,通常在head标签中即可,因此:

<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. 如您所见,该代码非常少。

When the Submit button (#mysub) is clicked, we quickly check each field to see if it validates. 单击提交按钮(#mysub)后,我们会快速检查每个字段以查看其是否有效。 If any field fails validation, we can return control to the user with the field colored and in focus. 如果任何字段未通过验证,我们可以将控件返回给用户,且该字段为彩色且焦点突出。

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). 如果所有字段均通过验证,那么我们将在表单ID上发出submit()方法,然后将其移至(在action="somepage.php"属性中指定的位置)。

Note that I added some quick/dirty code at bottom to remove any css colorization from failed validations. 请注意,我在底部添加了一些快速/肮脏的代码,以从失败的验证中删除任何CSS着色。 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. 这不是很有效(尽管它当然不会伤害任何东西),仅用于演示可能的方法。

Hmmmmm. 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 jsFiddle在这里

HTML: 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: 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'});
});

Note that there is also a jQuery validation plugin that looks very professional. 请注意,还有一个看起来非常专业的jQuery验证插件。 I haven't played with it myself, always preferring to code my own stuff, but here is the link: 我自己没有玩过,总是喜欢编写自己的东西,但这是链接:

http://jqueryvalidation.org/documentation/ http://jqueryvalidation.org/documentation/

Note the very cool demo 注意非常酷的演示

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 : 关于您的评论和在pastebin上发布的代码

(Sorry for the long answer, but I want it to be clear. Please read carefully.) (很抱歉,答案很长,但是我想清楚。请仔细阅读。)

(1) Please wrap your javascript code in a document.ready function. (1)请将您的javascript代码包装在document.ready函数中。 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). 否则,代码将在DOM完全存在之前执行,并且事件触发器将不会绑定到控件(因为它们在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) Your checkbox still has the value="yes" attribute that breaks the javascript. (2)您的复选框仍然具有value="yes"属性,该属性会破坏javascript。 Please change this: 请更改此:

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

to this: 对此:

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

(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. (3)不必为<input value="Invia">按钮<input value="Invia"> type="submit" ,也无需在该控件上使用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'] ). 首先是name=属性:仅在将数据从该控件传递到处理表单的PHP(?)文件时才有用:( $_SERVER['SCRIPT_NAME'] )。 The name= part is the variable name, and the value of the control is the variable value. name= part是变量名,控件的值是变量值。 The button has no data to pass along, so does not need to have a variable name assigned to it. 该按钮没有要传递的数据,因此不需要为其分配变量名。

Next, the type="submit" : This is not required, because you can use jQuery to submit the form any time you want. 接下来, type="submit" :这不是必需的,因为您可以随时使用jQuery提交表单。 In the old days, before javascript/jQuery, we had forms. 在过去,在使用javascript / jQuery之前,我们有表格。 Back in those days, the only way to make the form submit was to use the type="submit" attribute. 在那时候,提交表单的唯一方法是使用type="submit"属性。 There was no such command as: $('#myFormId').submit(); 没有这样的命令: $('#myFormId').submit(); -- but today there is. -但是今天有。 So change that attribute to type="button" and let jQuery submit the form for you. 因此,将该属性更改为type="button"然后让jQuery为您提交表单。 Trust me, this works! 相信我,这有效!

Another thing to consider: once you use type="submit" you must deal with the form's default actions when clicking that button. 要考虑的另一件事:一旦使用type="submit" ,则在单击该按钮时必须处理表单的默认操作。 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.) (您必须使用event.preventDefault()覆盖默认行为-您稍后可以阅读。)

(4) Checkbox values must be checked using one of these methods . (4)必须使用以下方法之一检查复选框的值。 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) jQuery's submit() method won't work IF any element uses =submit as either its name= or id= attribute. (5)如果任何元素使用=submit作为其name =或id =属性,则jQuery的submit()方法将不起作用

This is a weird thing, but you need to know it. 这是一件奇怪的事情,但是您需要了解它。 I just learned it (again) while troubleshooting my jsFiddle example. 我刚刚(再次)在对我的jsFiddle示例进行故障排除时了解了它。

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". 如果要使用jQuery通过.submit()方法提交表单(并且我们这样做),则表单中的任何元素都不能将name=id=属性设置为“ submit”。 The INPUT button had both name= and id= set to submit; INPUT按钮将name = id =都设置为提交; that is why it wasn't working. 这就是为什么它不起作用。

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

See the revised code example in the jsFiddle: 请参阅jsFiddle中的修改后的代码示例:

Revised jsFiddle here 修订jsFiddle在这里

Please Please Please study the above jsFiddle. Please Please请学习上面的jsFiddle。 You should be able to dump the genvalidator plugin entirely. 您应该可以完全转储genvalidator插件。 If you understand the jsFiddle completely, you will be in a new place as a programmer. 如果您完全了解jsFiddle,那么您将成为程序员的一个新地方。

If you're using jQuery, try checking this way: 如果您使用的是jQuery,请尝试通过以下方式进行检查:

function validate(form) { 
    if(!$('[name="agree"]').prop('checked')){
        alert("Please check the terms and conditions");
        return false;
    } 
    return true;
}

or try using 或尝试使用

function validate(form) {
    if(!$('[name="agree"]')[0].checked){
        alert("Please check the terms and conditions");
        return false;
    }
    return true;
} 

Since you've tagged the question with JQuery, this should work for you: 既然您已经用JQuery标记了问题,那么这应该对您有用:

function validate(form) { 
    if ($("#agree :checked").length < 1) {
        alert("Please check the terms and conditions");
        return false;
    } 
    return true;
}

I tend to use this approach because it also works for multiple checkboxes or radio button groups as well. 我倾向于使用这种方法,因为它也适用于多个复选框或单选按钮组。 Note, however, that it does not care about what was checked, just that something was checked . 但是请注意,它并不关心已检查的内容,仅关心已检查的内容。 . . in the case of a single checkbox, this acts as a "required to be checked" validation as well. 在单个复选框的情况下,它也充当“必需检查”验证。

This is untested but I think it would look something like this: 这未经测试,但我认为它看起来像这样:

function DoCustomValidation() {
    var frm = document.forms["myform"];
    if(document.form1.agree.checked != true) {
        sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1);
        return false;
    }else{
        return true;
    }
}

Note that you must customize this line to have the correct name of your own form: 请注意,您必须自定义此行以使用您自己的表单的正确名称:

var frm = document.forms["myform"];

Plus, you also need to associate the validation function with the validator object: 另外,您还需要将验证功能与验证器对象关联:

frmvalidator.setAddnlValidationFunction("DoCustomValidation");

Source: genvalidator documentation 来源: genvalidator文档

Add a new div for error location above your input tag like this : 在输入标签上方添加一个用于错误位置的新div,如下所示:

<div name="formname_inputname_errorloc" class="errorstring">
//<your input tag goes here>

Make sure u have the css for errorstring class in your css file. 确保您的css文件中有errorstring类的css。 and the other req js files 和其他req js文件

Try to search the demo for gen validator it has been totally explained in the demo 尝试在演示中搜索gen验证器,该示例已对它进行了全面说明

frmvalidator.addValidation(“同意”,“ selmin = 1”,“请选择复选框”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM