我的验证属性与客户端

时间:2015-03-19 22:05:20

标签: asp.net-mvc-5 unobtrusive-validation validationattribute

我的页面有业务规则 - 日期控件应按升序排列。即输入的值为Date1<输入值到Date2< DATE3

我的属性:

public class CompareDateAttribute : ValidationAttribute, IClientValidatable
{
    public CompareDateAttribute(string datesString)
    {
        _datesString = datesString;
    }
    private string _datesString;

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule()
        {
            //ErrorMessage = this.FormatErrorMessage(metadata.DisplayName),
            ErrorMessage = String.Format("Invalid date {0}", metadata.PropertyName),
            ValidationType = "datecomparer"
        };
        rule.ValidationParameters.Add("dates", _datesString);
        yield return rule;
    }
}

客户方:

$.validator.addMethod("datecomparer", function (value, element, param) {
    //var valid = true;
    var arrElements = param.split(',');
    var datePreviousStr = null;
    $.each(arrElements, function (index, v) {
        if (datePreviousStr == null)
        {
            datePreviousStr = $('#' + v).val();
        }
        else
        {
            var dateCurrentStr = $('#' + v).val();
            if (dateCurrentStr == '')
            {
                return false;
            }

            var dateCurrent = $.datepicker.parseDate("mm/dd/yy", dateCurrentStr);
            var datePrevious = $.datepicker.parseDate("mm/dd/yy", datePreviousStr);

            if (dateCurrent < datePrevious)
            {
                return false;
            }
            else
            {
                datePreviousStr = dateCurrentStr;
            }

        }
    });

    return true;
});

$.validator.unobtrusive.adapters.addSingleVal("datecomparer", "dates");

型号:

public class Valid6
{
    [CompareDate("Date1,Date2,Date3")]
    public DateTime Date1 { get; set; }
    [CompareDate("Date1,Date2,Date3")]
    public DateTime Date2 { get; set; }
    [CompareDate("Date1,Date2,Date3")]
    public DateTime Date3 { get; set; }
}

并查看(必要部分):

<div class="form-horizontal">
    <h4>Valid6</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Date1, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date1, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date1, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Date2, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date2, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date2, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Date3, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date3, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date3, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

也是结果HTML的一部分:

<input class="form-control text-box single-line valid" data-val="true" data-val-date="The field Date3 must be a date." data-val-datecomparer="Invalid date Date3" data-val-datecomparer-dates="Date1,Date2,Date3" data-val-required="The Date3 field is required." id="Date3" name="Date3" type="datetime" value="">

但当我输入Date1 = '11 / 11/2010'和Date2 = '11 / 11/2009'调试器说,该datecomparer方法返回false,但没有出现验证器消息。 为什么以及如何解决?

1 个答案:

答案 0 :(得分:0)

找到解决方案 - “返回false;” inside循环只返回循环,然后在方法结束时找到“return true”。

应该是:

$.validator.addMethod("datecomparer", function (value, element, param) {
    var valid = true;
    var arrElements = param.split(',');
    var datePreviousStr = null;
    $.each(arrElements, function (index, v) {
        if (datePreviousStr == null)
        {
            datePreviousStr = $('#' + v).val();
        }
        else
        {
            var dateCurrentStr = $('#' + v).val();
            if (dateCurrentStr == '')
            {
                valid = false;
                return;
            }

            var dateCurrent = $.datepicker.parseDate("mm/dd/yy", dateCurrentStr);
            var datePrevious = $.datepicker.parseDate("mm/dd/yy", datePreviousStr);

            if (dateCurrent < datePrevious)
            {
                valid = false;
                return;
            }
            else
            {
                datePreviousStr = dateCurrentStr;
            }

        }
    });

    return valid;
});

$.validator.unobtrusive.adapters.addSingleVal("datecomparer", "dates");