ASP.Net Core 本地化日期格式验证不起作用

问题描述 投票:0回答:1

我正在使用 data-val-required 替换必填字段的标准消息,并显示一条法语自定义消息,效果很好。当在我的字段中输入的日期无效但它不起作用时,我还使用 data-val-date 属性执行相同的操作。有什么想法吗?

<input id="datDebt" type="text" class="form-control datepicker valid" data-val="true" data-val-required="BD-Le champ Du est obligatoire." data_val_date="BD-Le format du champ Du doit être AAAA-MM-JJ." name="Client.DatDebutClint" value="" aria-autocomplete="none" placeholder="AAAA-MM-JJ" style="min-width: 7em;" maxlength="10" aria-describedby="datDebt-error" aria-invalid="false">
[DisplayName("Du")]
[DataType(DataType.DateTime)]

public DateTime? DatDebutClint { get; set; } = null;

我已包含 jquery.validation 脚本,将 datatype 属性添加到我的模型属性中

asp.net-core unobtrusive-validation
1个回答
0
投票

你还没有实现验证逻辑,是的,你可以直接修改jquery并通过自定义js文件获取客户端验证。但在我的测试中,模型格式验证仍然存在,并且创建后日期将无法正确显示。

默认的日期类型验证就像日历一样,为了满足您的需求,建议实现自定义客户端验证。这是我的代码示例。

1.型号

using System.ComponentModel.DataAnnotations;

namespace Yournamespace.Models
{
    public class DateM
    {
        public int Id { get; set; }
        [Display(Name = "Du", Prompt = "AAAA-MM-JJ")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        [CustomDate]
        public DateTime? DatDebutClint { get; set; } = null;
    }
}

2.查看

@model Yournamespace.Models.DateM

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>DateM</h4>
<hr />
<body>
    <div class="row">
        <div class="col-md-4">
            <form asp-action="Create" id="DateVali">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>

                   //this part to implement the validation
                <div class="form-group">
                    @Html.LabelFor(m => m.DatDebutClint)
                    @Html.TextBoxFor(m => m.DatDebutClint)
                    @Html.ValidationMessageFor(m => m.DatDebutClint)
                </div>

                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
</body>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

3.自定义日期属性.cs

using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System.ComponentModel.DataAnnotations;

public class CustomDateAttribute : ValidationAttribute, IClientModelValidator //1. add this interface
{
   // It is an easy logic of formation of server side
    public override bool IsValid(object value)
    {
        if (value is DateTime dateonly)
        {
            var semp = dateonly.ToString().Split(" ").ToList();
            var sline = semp[0].Split("/").ToList();
            if (int.Parse(sline[0]) <= 12 &&
                int.Parse(sline[0]) > 0 &&
                int.Parse(sline[1]) <= 31 &&
                int.Parse(sline[1]) > 0 &&
                int.Parse(sline[2]) <= 9999 &&
                int.Parse(sline[2]) > 1900)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }
    public override string FormatErrorMessage(string name)
    {
        return "BD-Le format du champ Du doit être AAAA-MM-JJ.";
    }
    //2. implement this method
    public void AddValidation(ClientModelValidationContext context)
    {
        var fieldName = context.Attributes["name"];
        context.Attributes.TryAdd("data-val", "true");
        context.Attributes.TryAdd("data-val-customdate", FormatErrorMessage(fieldName));
    }
}
4.customValidator.js
//Add the file in wwwroot/js folder,It is an easy logic of formation of client side
$.validator.addMethod('customdate', function (value, element, params) {
    var isDate = new Date(value).toString();
    var timeList = value.split('-');
    if (isDate != 'Invalid Date' && timeList.length == 3)
    {
        if (parseInt(timeList[0]) < 9999 &&
            parseInt(timeList[0]) > 1900 &&
            parseInt(timeList[1]) < 13 &&
            parseInt(timeList[1]) > 0 &&
            parseInt(timeList[2]) < 32 &&
            parseInt(timeList[2]) > 0)
        {
            return true;
        }
        else {
            return false;
        }
    }
    return false;
});
//here to implement the logic
$.validator.unobtrusive.adapters.add('customdate', function (options) {
    options.rules['customdate'] = [];
    options.messages['customdate'] = options.message;
});

5._ValidationScriptsPartial.cshtml

//using the js file in your ValidationScriptsPartial under Views/Shared
<script src="~/js/customValidator.js"></script>

测试

© www.soinside.com 2019 - 2024. All rights reserved.