簡體   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