加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何使用FluentValidation在ClientSide中验证日

发布时间:2020-12-16 04:09:46 所属栏目:asp.Net 来源:网络整理
导读:题 下面的代码工作正常服务器端而不是客户端.为什么? 当我提交表单时,控制权转到BeAValidDate函数以检查日期是否有效.有没有办法验证日期而无需使用Fluent验证进入服务器? 脚本 script src="jquery-1.7.1.min.js" type="text/javascript"/scriptscript src

下面的代码工作正常服务器端而不是客户端.为什么?

当我提交表单时,控制权转到BeAValidDate函数以检查日期是否有效.有没有办法验证日期而无需使用Fluent验证进入服务器?

脚本

<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>

模型

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);
    }
}

调节器

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);
    }
}

视图

@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" />
}

解决方法

使用更大然后或等于验证器的技巧.适合我.

Global.asax – 应用程序启动事件

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

模型

[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; }
}

规则

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,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;
    }
}

控制器动作方法

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);
}

视图

@using (Html.BeginForm("Index",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 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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读