JQuery验证 - 动态字段似乎打破了验证

时间:2014-09-04 09:55:24

标签: javascript jquery jquery-validate unobtrusive-validation

我有这个:

<div id="FormContainer">

    <button type="button" data-action="PrintWeightRange">Add Weight Range</button>

    <form id="DynamicForm" action="php/printinputs.php" method="POST">
        <!-- Fields are loaded in via JQuery and AJAX -->
    </form>

</div>

其他功能会在表单中附加输入和按钮。单击提交按钮时,JQuery绑定的函数会将字段附加到表单。

填充时表单如下所示:

<div id="FormContainer">

<button type="button" data-action="PrintWeightRange">Add Weight Range</button>

<form id="DynamicForm" action="php/printinputs.php"
method="POST">

    <button type="button" data-action="FormSubmit">Submit</button>

    <fieldset data-purpose="ShippingMethodDetails">
        <input type="text" value="Express Shipping" data-purpose="ShippingMethodName">
        <select data-purpose="ShippingMethodType">
            <option value="">Select a Shipping Method Type</option>
            <option value="opt1">Fixed</option>
            <option value="opt2">Weight and Location Based</option>
        </select>
        <select data-purpose="ShippingMethodCountry">
            <option value="">Select a Location</option>
            <option value="opt1">Country 1</option>
            <option value="opt2">Country 2</option>
            <option value="opt3">Country 3</option>
        </select>
        <select data-purpose="ShippingMethodRegion">
            <option value="">Select a Region</option>
            <option value="opt1">Region 1</option>
            <option value="opt2">Region 2</option>
            <option value="opt3">Region 3</option>
        </select>
    </fieldset>

    <fieldset data-purpose="ShippingMethodWeightRange">
        <input data-purpose="LowerWeight" type="number">
        <select data-purpose="WeightRangeType" data-action="ChangeWeightRangeType">
            <option value="andup">and up</option>
            <option value="to" selected="selected">to</option>
        </select>
        <input data-purpose="UpperWeight" type="number">
        <input data-purpose="WeightRangePrice" type="number">
        <button type="button" data-action="RemoveThis">Remove</button>
    </fieldset>

</form>

button[data-action='SubmitForm']有一个绑定到它的函数,它使用JQuery each()函数循环遍历表单中的所有选择和输入,并将它们添加到两个对象 - DynamicFormValidationRules以传递给AJQuery表单的JQuery验证和DynamicFormAjaxData

DynamicFormValidationRules = {
    "Fieldset1_ShippingMethodDetails_ShippingMethodName": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodType": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodCountry": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodRegion": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_LowerWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangeType": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_UpperWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangePrice": {
        "required": true
    }
}

DynamicFormAjaxData = {
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodCountry: ""
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodName: "Express Shipping"
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodRegion: ""
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodType: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_LowerWeight: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_UpperWeight: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_WeightRangePrice: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_WeightRangeType: "to"
}

将所有这些值编组到对象后,我调用validate函数:

$("#DynamicForm").validate({
    rules: DynamicFormValidationRules,
    submitHandler : ValidateDynamicFormHandler,
});

第一次按预期验证。

但是,当我向表单添加另一个送货方式并再次调用这些功能时,新字段不会被选中并标记为有效,即使它们不是:

DynamicFormValidationRules = {
    "Fieldset1_ShippingMethodDetails_ShippingMethodName": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodType": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodCountry": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodRegion": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_LowerWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangeType": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_UpperWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangePrice": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_LowerWeight": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_WeightRangeType": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_UpperWeight": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_WeightRangePrice": {
        "required": true
    }
}

以下是相关的JavaScript:

function FormSubmit(event) {
    AssignFieldIDs()
}

function AssignFieldIDs() {

    console.log("AssignFieldIDs()");

    var myReturn = {};

    var NumFieldsets = $("#DynamicForm").find("fieldset").length;

    $("#DynamicForm").find("fieldset").each(function(index, element){

        var myFieldset = element;
        var myFieldsetIndex = index;
        var myFieldsetNumber = myFieldsetIndex + 1;
        var myFieldsetPurpose = $(element).attr("data-purpose");
        var myFieldsetName;

        if (NumFieldsets > 1) {
            myFieldsetName = myFieldsetPurpose + myFieldsetNumber
        } else {
            myFieldsetName = myFieldsetPurpose;
        }

        console.log(element);

        $(myFieldset).attr("id", "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose);

        $(myFieldset).find("input, select, textarea").each(function(index,element){

            myField = element
            myFieldIndex = index;
            myFieldNumber = index + 1;
            myFieldPurpose = $(element).attr("data-purpose");
            myFieldName = "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose + "_" + myFieldPurpose; //+ myFieldsetNumber;

            // $(element).attr("name", myFieldsetName + "_" + myFieldName);
            $(element).attr("name", myFieldName);
            $(element).attr("id", myFieldName);

            DynamicFormAjaxData[myFieldsetName + "_" + myFieldName] = $(myField).val();
            DynamicFormValidationRules[myFieldName] = {required : true};

        }); 

    });

    PrepareFormValues();

}

function PrepareFormValues(event) {

    console.log("PrepareFormValues()")

    console.log("DynamicFormAjaxData")
    console.log(DynamicFormAjaxData)

    console.log("DynamicFormValidationRules");
    console.log(DynamicFormValidationRules);

    $("#DynamicForm").validate({
        rules: DynamicFormValidationRules,
        submitHandler : ValidateDynamicFormHandler,
    });

    console.log('$("#DynamicForm").valid()');
    console.log($("#DynamicForm").valid());

    if ($("#DynamicForm").valid() === true ) {
        $("#DynamicForm").submit();
    }
    else
    if ($("#DynamicForm").valid() === false ) {

    }


}

感谢阅读!

1 个答案:

答案 0 :(得分:0)

非常感谢@SSA带领我找到答案。

我没有使用JQuery函数将所有规则附加到对象并传递它,而是使用JQueryValidate的rules()方法分别为每个字段添加了规则。

function AssignFieldIDs() {

    console.log("AssignFieldIDs()");

    var NumFieldsets = $("#DynamicForm").find("fieldset").length;

    // Form is validated here, without rules
    $("#DynamicForm").validate({
        submitHandler : ValidateDynamicFormHandler,
    });

    $("#DynamicForm").find("fieldset").each(function(index, element){

        var myFieldset = element;
        var myFieldsetIndex = index;
        var myFieldsetNumber = myFieldsetIndex + 1;
        var myFieldsetPurpose = $(element).attr("data-purpose");
        var myFieldsetName;

        if (NumFieldsets > 1) {
            myFieldsetName = myFieldsetPurpose + myFieldsetNumber;
        } else {
            myFieldsetName = myFieldsetPurpose;
        }

        console.log(element);

        $(myFieldset).attr("id", "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose);

        $(myFieldset).find("input, select, textarea").each(function(index,element){

            // Creates temporary vars for field naming in the objects.
            myField = element;
            myFieldIndex = index;
            myFieldNumber = index + 1;
            myFieldPurpose = $(element).attr("data-purpose");
            myFieldName = "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose + "_" + myFieldPurpose; //+ myFieldsetNumber;

            // Sets names and ids in the HTML for use by the 
            $(element).attr("name", myFieldName);
            $(element).attr("id", myFieldName);

            // Validates each field.
            $(element).rules("add", {required:true});

            // Adds to an object for making an AJAX post.
            DynamicFormAjaxData[myFieldsetName + "_" + myFieldName] = $(myField).val();


        }); 

    });

    PrepareFormValues();

}