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

时间:2013-10-08 21:48:42

标签: javascript jquery contact-form

我正在使用genvalidator对表单中的输入字段进行一些测试。问题是我无法找到一种方法来测试是否已选中复选框。这就是所有字段的设置方式:

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强制使用它?

这是处理表单处理的部分(简而言之:如果没有错误,那就没关系):

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


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

尝试使用这个JS代码没有运气:

function validate(form) { 

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


return true;
}

如果可能,我想使用genvalidator函数。 :)

5 个答案:

答案 0 :(得分:1)

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

你会考虑使用jQuery吗?如果你还没有踢它的轮胎,它比听起来容易得多 - 而且比普通的js更加均匀/快速的打字。

要使用jQuery,您只需要在文档中包含jQuery库,通常在头标记中包含:

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

然后,您可以轻松创建自己的验证例程,完全控制您正在做的事情。


以下是您学习的工作示例。如您所见,代码非常简单。

单击“提交”按钮(#mysub)后,我们会快速检查每个字段以查看其是否有效。如果任何字段验证失败,我们可以将控件返回给用户,并将字段设置为彩色且焦点对齐。

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

请注意,我在底部添加了一些快速/脏代码,以从失败的验证中删除任何css着色。无论字段是否具有验证着色,每次退出字段时此代码都会运行。这不是很有效(尽管它肯定不会伤害任何东西),并且只是为了展示可能的东西。

Hmmmmm。我认为拥有具有某些属性的类会更有效,并且如果验证失败则添加/删除该类。好吧,我非常喜欢这个想法,我使用该方法创建了a new 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验证插件。我自己没有玩过它,总是喜欢编写我自己的东西,但这里是链接:

http://jqueryvalidation.org/documentation/

请注意very cool demo

只是让你知道会发生什么:实现这个插件会比我上面建议的方法更难。


`      ANSWER TO YOUR COMMENT QUESTION:                                         `

关于您的评论和the code posted at pastebin

(很抱歉答案很长,但我希望它清楚。请仔细阅读。)

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

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)您的复选框仍然具有打破javascript的value="yes"属性。请更改此信息:

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

到此:

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

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

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

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

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

(4)必须使用one of these methods检查复选框值。复选框没有值。这是我的错,我应该在我的例子中写一个复选框。

$('#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的submit()方法不起作用如果任何元素使用=submit作为其name =或id = attribute。

这是一件奇怪的事,但你需要知道它。我在对jsFiddle示例进行故障排除时(再次)学习了它。

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

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

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

<强> Revised jsFiddle here

请请研究以上jsFiddle。您应该能够完全转储genvalidator插件。如果您完全了解jsFiddle,那么您将作为程序员进入一个新的位置。

答案 1 :(得分:0)

如果您正在使用jQuery,请尝试以这种方式检查:

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

或尝试使用

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

答案 2 :(得分:0)

由于您使用JQuery标记了问题,这应该对您有用:

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

我倾向于使用这种方法,因为它也适用于多个复选框或单选按钮组。但请注意,它并不关心检查的内容,只是检查了一些内容。 。 。在单个复选框的情况下,这也是“需要检查”验证。

答案 3 :(得分:0)

这是未经测试但我认为它看起来像这样:

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

请注意,您必须自定义此行才能拥有自己表单的正确名称:

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

另外,您还需要将验证功能与验证器对象相关联:

frmvalidator.setAddnlValidationFunction("DoCustomValidation");

来源:genvalidator documentation

答案 4 :(得分:0)

为输入标记上方的错误位置添加一个新div,如下所示:

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

确保你的css文件中有错误字符串类的css。和其他req js文件

尝试在演示中搜索gen验证器,它已在演示中完全解释