Jquery Unobstrusive验证:数组必须包含1个元素

时间:2016-08-11 11:42:53

标签: jquery validation asp.net-mvc-4

我有以下viewmodel定义。我的情况是该数组必须包含至少一个项目,否则必须显示错误。

public class GroupVM
{
    [Required(ErrorMessage="Please enter GroupName")]
    public string GroupName { get; set; }

    [RequiredArray(ErrorMessage="Please select Centre Code")]
    public int[] CentreCodeId { get; set; }
    public SelectList CentreCodeList { get; set; }

    public DateTime TransactionDate { get; set; }
}

我已经执行了服务器端验证并且工作正常,但客户端验证无效。

public class RequiredArray : ValidationAttribute,IClientValidatable
{
    public override bool IsValid(object value)
    {
        var list = value as IList;
        if (list != null)
        {
            return list.Count > 0;
        }
        return false;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ValidationType = "emptyarray",
            ErrorMessage = this.ErrorMessage
        };            
        yield return rule;
    }
}

客户端脚本如下

<script type="text/javascript">
$(function () {
    jQuery.validator.addMethod("emptyarray", function (value, element, param) {
        if (element.value == null) {
            return false;
        }
        return true;
    });
    jQuery.validator.unobtrusive.adapters.addBool("emptyarray");


})

Razor View如下

  @Html.ListBoxFor(m => m.CentreCodeId
                        , Model.CentreCodeList
                        , new { @class = "form-control select2 courseList", @id = "ddlCentreCode" })
  @Html.ValidationMessageFor(m => m.CentreCodeId)

HTML标记如下

<select class="form-control select2 courseList valid" data-val="true" data-val-emptyarray="Please select centre code" id="ddlCentreCode" multiple="multiple" name="CentreCodeId"><option value="5">NSTAJ001</option>
<option value="6">NSTVJ002</option>
<option value="7">NSNVY004</option>
<option value="8">NSTDJ005</option>
</select>

任何想法为什么客户端验证不起作用。

1 个答案:

答案 0 :(得分:1)

你需要删除周围的$(function () {(脚本只需要在<script>标签内和jquery.validate*脚本之后,你还需要检查并清空字符串,而不是null

<script src="/Scripts/jquery-{version}.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

<script type="text/javascript">
    jQuery.validator.addMethod("emptyarray", function (value, element, param) {
        if (element.value === "") { // change
            return false;
        }
        return true;
    });
    jQuery.validator.unobtrusive.adapters.addBool("emptyarray");
</script>

旁注:我假设var list = value as IList;是一个拼写错误(它会引发异常)并且它真的是var list = value as IList<int>;