如何使用FluentValidation验证日期在客户方? [英] How to validate Date in ClientSide using FluentValidation?

查看:740
本文介绍了如何使用FluentValidation验证日期在客户方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code是工作的罚款服务器端,而不是客户端。为什么呢?

结果
当我提交表单,控制转到 BeAValidDate 函数来检查日期是否有效。有没有什么办法验证不使用将服务器中的日期流利的验证

脚本

 <脚本SRC =jQuery的-1.7.1.min.js类型=文/ JavaScript的>< / SCRIPT>
<脚本SRC =jquery.validate.js类型=文/ JavaScript的>< / SCRIPT>
<脚本SRC =jquery.validate.unobtrusive.js类型=文/ JavaScript的>< / SCRIPT>

型号

 公共类PersonValidator:AbstractValidator<&人GT;
{
    公共PersonValidator()
    {
        RuleFor(X => x.FromDate)
            。不是空的()
            .WithMessage(日期是必需的!)
            。必须(BeAValidDate)
            .WithMessage(无效的日期);
    }    私人布尔BeAValidDate(字符串值)
    {
        DateTime的日期;
        返回DateTime.TryParse(价值,过时);
    }
}

控制器

 公共类PersonController:控制器
{
    公众的ActionResult指数()
    {
       返回查看(新的Person {寄件者= DateTime.Now.AddDays(2)的ToString()});
    }    [HttpPost]
    公众的ActionResult指数(人P)
    {
        返回查看(P);
    }
}

查看

  @using(Html.BeginForm(指数,人,FormMethod.Post))
{
    @ Html.LabelFor(X => x.FromDate)
    @ Html.EditorFor(X => x.FromDate)
    @ Html.ValidationMessageFor(X => x.FromDate)    <输入类型=提交名称=提交值=提交/>
}


解决方案

使用计谋大或者等于验证。我的作品。

的Global.asax - 应用程序启动事件

  FluentValidationModelValidatorProvider.Configure(X =>
{
    x.Add(typeof运算(GreaterThanOrEqualValidator)
            (元数据,语境,规则,验证)=>
                新LessThanOrEqualToFluentValidationPropertyValidator
                (
                    元数据,语境,规则,验证
                )
            );
});

型号

  [验证(typeof运算(MyViewModelValidator))]
公共类MyViewModel
{
    [显示(NAME =开始日期)]
    [DisplayFormat(DataFormatString ={0:YYYY-MM-DD},
                                                  ApplyFormatInEditMode = TRUE)]
    公开日期时间起始日期{搞定;组; }    [DisplayFormat(DataFormatString ={0:YYYY-MM-DD},
                                                  ApplyFormatInEditMode = TRUE)]
    公众的DateTime DateToCompareAgainst {搞定;组; }
}

规则

 公共类MyViewModelValidator:AbstractValidator< MyViewModel>
{
    公共MyViewModelValidator()
    {
        RuleFor(X => x.StartDate)
            .GreaterThanOrEqualTo(X => x.DateToCompareAgainst)
            .WithMessage(无效的开始日期);
    }
}

FluentValidationPropertyValidator

 公共类GreaterThenOrEqualTo:FluentValidationPropertyValidator
{
    公共GreaterThenOrEqualTo(ModelMetadata元,
                                ControllerContext controllerContext,
                                PropertyRule规则,
                                IPropertyValidator验证)
        :基地(元数据,controllerContext,规则,验证)
    {
    }    公共覆盖的IEnumerable< ModelClientValidationRule>
                                                    GetClientValidationRules()
    {
        如果(!this.ShouldGenerateClientSideRules())
        {
            产生中断;
        }        VAR验证=验证为GreaterThanOrEqualValidator;        VAR的errorMessage =新MessageFormatter()
            .AppendPropertyName(this.Rule.GetDisplayName())
            .BuildMessage(validator.ErrorMessageSource.GetString());        VAR规则=新ModelClientValidationRule {
            的ErrorMessage =的errorMessage,
            ValidationType =greaterthanorequaldate};
        rule.ValidationParameters [等] =
            CompareAttribute.FormatPropertyForClientValidation(
                validator.MemberToCompare.Name);
        产生回报规则;
    }
}

控制器的操作方法

 公众的ActionResult指数()
{
    VAR模型=新MyViewModel
    {
        起始日期= DateTime.Now.AddDays(2),
        DateToCompareAgainst =默认值(DateTime的)//默认日期
    };
    返回查看(模型);
}
[HttpPost]
公众的ActionResult指数(Practise.Areas.FluentVal.Models.MyViewModel P)
{
    返回查看(P);
}

查看

  @using(Html.BeginForm(指数,人,FormMethod.Post,
                                                新{ID =FormSubmit}))
{
    @ Html.Hidden(DateToCompareAgainst,Model.DateToCompareAgainst);
    @ Html.LabelFor(X => x.StartDate)
    @ Html.EditorFor(X => x.StartDate)
    @ Html.ValidationMessageFor(X => x.StartDate)
    <按钮式=提交>
        OK< /按钮>
}

脚本

 <脚本SRC =jQuery的-1.4.1.min.js类型=文/ JavaScript的>< / SCRIPT>
<脚本SRC =jquery.validate.js类型=文/ JavaScript的>< / SCRIPT>
<脚本SRC =jquery.validate.unobtrusive.js类型=文/ JavaScript的>< / SCRIPT>
<脚本类型=文/ JavaScript的>
    (函数($){
        $ .validator.unobtrusive.adapters.add('greaterthanorequaldate',
                                             ['其他'],功能(选件){
            VAR getModel preFIX =函数(字段名){
                返回fieldName.substr(0,fieldName.lastIndexOf()+1。);
            };            VAR appendModel preFIX =功能(价值preFIX){
                如果(value.indexOf(*)=== 0){
                    值= value.replace(*。,preFIX);
                }
                返回值;
            }            VAR preFIX = getModel preFIX(options.element.name)
                其他= options.params.other,
                fullOtherName = appendModel preFIX(其他,preFIX)
            元素= $(options.form).find(:输入[名称=+ fullOtherName +
                                                        ])[0];            options.rules ['greaterthanorequaldate'] =元素;
            如果(options.message!= NULL){
                options.messages ['greaterthanorequaldate'] = options.message;
            }
        });


  $ .validator.addMethod('greaterthanorequaldate',
                               功能(价值元素,则params){
            VAR日期=新的日期(值);
            VAR dateToCompareAgainst =新的日期($(PARAMS).VAL());            如果(isNaN(date.getTime())|| isNaN(dateToCompareAgainst.getTime())){
                返回false;
            }
            返回日期> = dateToCompareAgainst;
        });    })(jQuery的);
< / SCRIPT>

Question

The below code is working fine Server side and not Client side. Why ?


When I submit the form, control goes to BeAValidDate function to check the date is valid or not. Is there any way to Validate the date without going to server using Fluent Validation?

Scripts

<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.js" type="text/javascript"></script>

Model

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {
        RuleFor(x => x.FromDate)
            .NotEmpty()
            .WithMessage("Date is required!")
            .Must(BeAValidDate)
            .WithMessage("Invalid Date");
    }

    private bool BeAValidDate(String value)
    {
        DateTime date;
        return DateTime.TryParse(value, out date);
    }
}

Controller

public class PersonController : Controller
{
    public ActionResult Index()
    {
       return View(new Person { FromDate = DateTime.Now.AddDays(2).ToString()});
    }

    [HttpPost]
    public ActionResult Index(Person p)
    {
        return View(p);
    }
}

View

@using (Html.BeginForm("Index", "Person", FormMethod.Post))
{   
    @Html.LabelFor(x => x.FromDate)
    @Html.EditorFor(x => x.FromDate)
    @Html.ValidationMessageFor(x => x.FromDate)

    <input type="submit" name="Submit" value="Submit" />
}

解决方案

Trick using Greater Then Or Equal To Validator. Works for me.

Global.asax - Application Start Event

FluentValidationModelValidatorProvider.Configure(x =>
{
    x.Add(typeof(GreaterThanOrEqualValidator), 
            (metadata, Context, rule, validator) => 
                new LessThanOrEqualToFluentValidationPropertyValidator
                (
                    metadata, Context, rule, validator
                )
            );
});

Model

[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
    [Display(Name = "Start date")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", 
                                                  ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }

    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", 
                                                  ApplyFormatInEditMode = true)]
    public DateTime DateToCompareAgainst { get; set; }
}

Rule

public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
    public MyViewModelValidator()
    {
        RuleFor(x => x.StartDate)
            .GreaterThanOrEqualTo(x => x.DateToCompareAgainst)
            .WithMessage("Invalid start date");
    }
}

FluentValidationPropertyValidator

public class GreaterThenOrEqualTo : FluentValidationPropertyValidator
{
    public GreaterThenOrEqualTo(ModelMetadata metadata, 
                                ControllerContext controllerContext, 
                                PropertyRule rule, 
                                IPropertyValidator validator)
        : base(metadata, controllerContext, rule, validator)
    {
    }

    public override IEnumerable<ModelClientValidationRule> 
                                                    GetClientValidationRules()
    {
        if (!this.ShouldGenerateClientSideRules())
        {
            yield break;
        }

        var validator = Validator as GreaterThanOrEqualValidator;

        var errorMessage = new MessageFormatter()
            .AppendPropertyName(this.Rule.GetDisplayName())
            .BuildMessage(validator.ErrorMessageSource.GetString());

        var rule = new ModelClientValidationRule{
            ErrorMessage = errorMessage,
            ValidationType = "greaterthanorequaldate"};
        rule.ValidationParameters["other"] = 
            CompareAttribute.FormatPropertyForClientValidation(
                validator.MemberToCompare.Name);
        yield return rule;
    }
}

Controller Action Method

public ActionResult Index()
{
    var model = new MyViewModel
    {
        StartDate = DateTime.Now.AddDays(2),
        DateToCompareAgainst = default(DateTime)  //Default Date
    };
    return View(model);
}
[HttpPost]
public ActionResult Index(Practise.Areas.FluentVal.Models.MyViewModel p)
{
    return View(p);
}

View

@using (Html.BeginForm("Index", "Person", FormMethod.Post, 
                                                new { id = "FormSubmit" }))
{   
    @Html.Hidden("DateToCompareAgainst", Model.DateToCompareAgainst);      
    @Html.LabelFor(x => x.StartDate)
    @Html.EditorFor(x => x.StartDate)
    @Html.ValidationMessageFor(x => x.StartDate)
    <button type="submit">
        OK</button>
}

Script

<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script type="text/javascript">
    (function ($) {
        $.validator.unobtrusive.adapters.add('greaterthanorequaldate', 
                                             ['other'], function (options) {
            var getModelPrefix = function (fieldName) {
                return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
            };

            var appendModelPrefix = function (value, prefix) {
                if (value.indexOf("*.") === 0) {
                    value = value.replace("*.", prefix);
                }
                return value;
            }

            var prefix          = getModelPrefix(options.element.name),
                other           = options.params.other,
                fullOtherName   = appendModelPrefix(other, prefix),
            element = $(options.form).find(":input[name=" + fullOtherName + 
                                                        "]")[0];

            options.rules['greaterthanorequaldate'] = element;
            if (options.message != null) {
                options.messages['greaterthanorequaldate'] = options.message;
            }
        });


        $.validator.addMethod('greaterthanorequaldate', 
                               function (value, element, params) {
            var date = new Date(value);
            var dateToCompareAgainst = new Date($(params).val());

            if (isNaN(date.getTime()) || isNaN(dateToCompareAgainst.getTime())) {
                return false;
            }
            return date >= dateToCompareAgainst;
        });

    })(jQuery);
</script>

这篇关于如何使用FluentValidation验证日期在客户方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆