繁体   English   中英

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

[英]genvalidator: check for checkbox in form validation

我正在使用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函数。 :)

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

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

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

<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。 我认为拥有一个具有某些属性的类并在验证失败时添加/删除该类会更有效。 好的,我非常喜欢这个想法,因此我使用该方法创建了一个新的jsFiddle来演示其外观。

jsFiddle在这里

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/

注意非常酷的演示

就是这样,您知道会发生什么:实现此插件比我上面建议的方法更加困难。


`      ANSWER TO YOUR COMMENT QUESTION:                                         `

关于您的评论和在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)您的复选框仍然具有value="yes"属性,该属性会破坏javascript。 请更改此:

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

对此:

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

(3)不必为<input value="Invia">按钮<input value="Invia"> type="submit" ,也无需在该控件上使用name=属性。

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

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

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

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

$('#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()方法将不起作用

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

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

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

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

修订jsFiddle在这里

Please Please请学习上面的jsFiddle。 您应该可以完全转储genvalidator插件。 如果您完全了解jsFiddle,那么您将成为程序员的一个新地方。

如果您使用的是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;
} 

既然您已经用JQuery标记了问题,那么这应该对您有用:

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

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

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

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文档

在输入标签上方添加一个用于错误位置的新div,如下所示:

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

确保您的css文件中有errorstring类的css。 和其他req js文件

尝试在演示中搜索gen验证器,该示例已对它进行了全面说明

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

暂无
暂无

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

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