JQuery验证自定义方法在JQuery .load()之后不工作

本文关键字:JQuery 之后 工作 load 验证 自定义方法 | 更新日期: 2023-09-27 18:02:29

当使用jquery.load时,我试图获得JQueryValidate自定义验证属性似乎不工作。这是我的代码:

CreateViewModel.cs

public class CreateViewModel
{
    [DisplayName("Artwork")]
    public int ArtworkId { get; set; }
    [AtLeastOne("selectiongroup")]
    public bool IsPromo { get; set; }
    [AtLeastOne("selectiongroup")]
    public bool IsUpc { get; set; }
    [AtLeastOne("selectiongroup")]
    public bool IsCoupon { get; set; }
    public SelectList ArtworkSelectList { get; set; }
}

AtLeastOneAttribute.cs

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class AtLeastOneAttribute : ValidationAttribute, IClientValidatable
{
    public string GroupName { get; private set; }
    public AtLeastOneAttribute(string groupName)
    {
        GroupName = groupName;
    }
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = "At least one of Coupon or Upc or Promo is required.",
            ValidationType = "atleastone",
            ValidationParameters =
            {
                new KeyValuePair<string, object>("groupname", GroupName),
            }
        };
    }
}

Page.cshtml

<form method="POST" id="signCreationForm">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-6">
                @Html.LabelFor(model => model.ArtworkId)
                @Html.DropDownListFor(model => model.ArtworkId, Model.ArtworkSelectList, "Select an Artwork")
            </div>
        </div>
        <div class="row">
            <div class="col-lg-6"></div>
            <div>@Html.ValidationMessageFor(model => model.ArtworkId)</div>
        </div>
        <div class="row">
            <div class="col-lg-10">
                <label>Associated With:</label>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-4">
                @Html.LabelFor(model => model.IsUpc, "UPC")
                @Html.CheckBoxFor(model => model.IsUpc)
                @Html.ValidationMessageFor(model => model.IsUpc)
            </div>
            <div class="col-lg-4">
                @Html.LabelFor(model => model.IsCoupon, "Coupon")
                @Html.CheckBoxFor(model => model.IsCoupon)
                @Html.ValidationMessageFor(model => model.IsCoupon)
            </div>
            <div class="col-lg-4">
                @Html.LabelFor(model => model.IsPromo, "Promotion")
                @Html.CheckBoxFor(model => model.IsPromo)
                @Html.ValidationMessageFor(model => model.IsPromo)
            </div>
        </div>
    </div>
</form>
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
    $.validator.addMethod("atleastone", function (value, element, params) {
        return $("[data-val-atleastone-groupname="+params+"]:checked").length > 0;
    });
    $.validator.unobtrusive.adapters.add("atleastone", ["groupname"], function (options) {
        options.rules["atleastone"] = options.params.groupname;
        options.messages["atleastone"] = options.message;
    });
</script>

CallingPage。CSHTML(调用它的javascript)

        $("#create-ad[data-link]").on("click", function() {
            var link = $(this).data("link");
            $createDialog.load(link, function() {
                $createDialog.dialog("open");
                $.validator.unobtrusive.parse($("#signCreationForm"));
            });
        });
现在,这段代码在一个单独的项目中工作。在这个项目中,分部视图是通过jquery.load()事件加载的,由于某种原因,这会导致自定义方法永远不会执行。我之所以知道这一点,是因为对于使用atlestone属性装饰的每个属性,警报通常会触发一次。

页面上有什么特别需要做的吗?当使用jquery加载自定义jqueryvalidate验证时?

JQuery验证自定义方法在JQuery .load()之后不工作

请将您的自定义方法放入jquery document ready;;;;;;

例如

<script type="text/javascript">
$(document).ready(function(){
    $.validator.addMethod("atleastone", function (value, element, params) {
        alert("halp");
        return $(".grouped:checked").length > 0;
    });
    $.validator.unobtrusive.adapters.add("atleastone", ["groupname"], function (options) {
        alert("halp");
        options.rules["atleastone"] = "#" + options.params.groupname;
        options.messages["atleastone"] = options.message;
    });
});
</script>

这个场景答案https://stackoverflow.com/a/16105954/82333的建议副本得到了问题的前半部分,即add $.validator. unobtrusiusid .adapters。Add无法正常运行。然而,在那之后,其余的代码也不能运行了。

@Bhavin Solanki在调用页面中包含验证文件的注释修复了另一半问题,即提交时代码没有运行