ASP.Net Core localized date format validation not working

51 views Asked by At

I'm using the data-val-required to replace the standard message for required field and get a french custom message displayed and it works well. I'm also using the data-val-date attribute to do the same when the date entered in my field is invalid but it doesn't work. Any idea?

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

I've included the jquery.validation script, added the datatype attribute to my model property

1

There are 1 answers

0
Fengzhi Zhou On

You haven’t implement the validation logic, yes you can directly modify the jquery and get the client validation through a custom js file. However in my test, the model format validation still remains, and the date will not get displayed correctly after created.

The default datetype validation works like a calendar, to meet your need it is recommended to implement a custom client validation. Here is my code sample.

1.Model

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

@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.CustomDateAttribute.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>

Test

enter image description here