【问题标题】:MVC5 Validate- To date greater than from dateMVC5 Validate-To date 大于 from date
【发布时间】:2014-05-01 21:35:51
【问题描述】:

我的表单上有两个日期选择器字段,我想验证截止日期是否大于起始日期。

MVC5 中是否有任何验证属性可用于实现此目的?

我也希望这可以在客户端工作,请问有人可以帮助在 MVC 中启用客户端验证吗?

非常感谢

编辑:创建了自定义属性,但客户端验证不起作用。

public class ValidateToDateAttribute : ValidationAttribute, IClientValidatable
    {

        public string errorMessageKey { get; private set; }

        public ValidateToDateAttribute(string errorMessageKey)
        {
            this.errorMessageKey = errorMessageKey;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var viewModel = (TransactionViewModel)validationContext.ObjectInstance;
                if (viewModel.ToDate.CompareTo(viewModel.FromDate) < 0)
                {
                    return new ValidationResult(new ResourceManager(typeof(ValidationErrorMessages)).GetString(errorMessageKey));
                }
            }

            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var modelClientValidationRule = new ModelClientValidationRule
            {
                ValidationType = "validatetodate",
                ErrorMessage = new ResourceManager(typeof(ValidationErrorMessages)).GetString(errorMessageKey)
            };

            yield return modelClientValidationRule;
        }
    }
}

Bundle.Config

bundles.Add(new ScriptBundle("~/bundles/jqueryvalidation").Include(
                        "~/Scripts/jquery.validate.unobtrusive.min.js",
                        "~/Scripts/jquery.unobtrusive-ajax.min.js"));

查看模型

    [Display(ResourceType = typeof(DisplayLabelText), Name = "FromDate")]       
    public DateTime FromDate { get; set; }

    [Display(ResourceType = typeof(DisplayLabelText), Name = "ToDate")]
    [ValidateToDate("ToDateMustBeGreater")]
    public DateTime ToDate { get; set; }

在视图中:

<div class="col-sm-7 margin-top-10">
                        <div class="col-sm-12">
                            @Html.LabelFor(m => m.FromDate, new { @class = "col-sm-3 form-group control-label" })
                            <div class="col-sm-8">
                                @Html.TextBoxFor(m => m.FromDate, "{0:MMM dd yyyy}", new { @class = "datepicker", disabled = "disabled" })
                            </div>
                        </div>
                        <div class="col-sm-12">
                            @Html.LabelFor(m => m.ToDate, new { @class = "col-sm-3 form-group control-label" })
                            <div class="col-sm-8">
                                @Html.TextBoxFor(m => m.ToDate, "{0:MMM dd yyyy}", new { @class = "datepicker", disabled = "disabled" })
                                @Html.ValidationMessageFor(m => m.ToDate)
                            </div>
                        </div>
                        <button type="submit" class="apply-filter-button">Apply Filter</button>
                    </div>

【问题讨论】:

  • 我们不是来为您提供完整的教程或为您完成所有工作/研究。我们主要在这里帮助您编写一段代码或回答一个简洁的问题。见:stackoverflow.com/help/how-to-ask
  • 当您询问 MVC5 时,为什么要使用 MVC3 和 MVC4 标签?此处不允许发送垃圾邮件。
  • 无意标记垃圾邮件,我只是认为 mvc3 和 mvc4 的解决方案可能对 MVC5 仍然有效。
  • 编辑帖子并添加代码。
  • "我只是认为 mvc3 和 mvc4 的解决方案可能对 MVC5 仍然有效" ~ 是的,这几乎就是标签垃圾邮件的定义。

标签: validation asp.net-mvc-5


【解决方案1】:

我想通了,我错过了不显眼的 java 脚本代码: 请看下面,它可能对某些人有帮助。

public class ValidateToDateAttribute : ValidationAttribute, IClientValidatable
{       
    /// <summary>
    /// Initializes a new instance of the <see cref="ValidateToDateAttribute"/> class.
    /// </summary>
    /// <param name="errorMessageKey">The error message key.</param>
    public ValidateToDateAttribute(string errorMessageKey, string otherProperty)
    {
        this.ErrorMessageKey = errorMessageKey;
        this.FromDate = otherProperty;
    }

    /// <summary>
    /// Gets from date.
    /// </summary>
    /// <value>
    /// From date.
    /// </value>
    public string FromDate { get; private set; }

    /// <summary>
    /// Gets the error message key.
    /// </summary>
    /// <value>
    /// The error message key.
    /// </value>
    public string ErrorMessageKey { get; private set; }

    /// <summary>
    /// When implemented in a class, returns client validation rules for that class.
    /// </summary>
    /// <param name="metadata">The model metadata.</param>
    /// <param name="context">The controller context.</param>
    /// <returns>
    /// The client validation rules for this validator.
    /// </returns>
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var modelClientValidationRule = new ModelClientValidationRule
        {
            ValidationType = "validatetodate",
            ErrorMessage = new ResourceManager(typeof(ValidationErrorMessages)).GetString(this.ErrorMessageKey),               
        };

        modelClientValidationRule.ValidationParameters.Add("other", this.FromDate);
        yield return modelClientValidationRule;
    }

    /// <summary>
    /// Validates the specified value with respect to the current validation attribute.
    /// </summary>
    /// <param name="value">The value to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    /// <returns>
    /// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class.
    /// </returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var viewModel = (TransactionViewModel)validationContext.ObjectInstance;
            if (viewModel.ToDate.CompareTo(viewModel.FromDate) < 0)
            {
                return new ValidationResult(new ResourceManager(typeof(ValidationErrorMessages)).GetString(this.ErrorMessageKey));
            }
        }

        return ValidationResult.Success;
    }
}

JavaScript:

<script type="text/javascript">
jQuery.validator.addMethod('greaterThan', function (value, element, params) {        
    if (!/Invalid|NaN/.test(new Date(value))) {
        //return new Date(value) > new Date($("input[name='FromDate']").val());            
        return Date.parse(value) > Date.parse($(params).val());
    }       
    return isNaN(value) && isNaN($(fromDate)) || (parseFloat(value) > parseFloat($("input[name='FromDate']").val()));
}, '');

// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('validatetodate', ["other"], function (options) {       
    options.rules['greaterThan'] = "#" + options.params.other;
    options.messages['greaterThan'] = options.message;
});

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 2021-09-07
    • 1970-01-01
    • 2021-05-21
    • 2022-12-28
    • 2015-03-29
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多