客户端ModelValidation中具有dd / MM / yyyy格式日期的最小年龄验证

时间:2019-06-17 10:45:54

标签: c# asp.net validation date model

这是我的客户端验证

    (function ($) {
        // Here I will add code for client side validation for our custom validation (age range validation)

        $.validator.unobtrusive.adapters.add("minimumage", ["minage"], function (options) {
            options.rules["minimumage"] = options.params;
            options.messages["minimumage"] = options.message;
        });

        $.validator.addMethod("minimumage", function (value, elements, params) {
            if (value) {
                var valDate = new Date(value);
                if ((new Date().getFullYear() - valDate.getFullYear()) < parseInt(params.minage)
                ) {
                    return false;
                    //validation failed
                }
            }
            return true;
        });
    })(jQuery);

Model.cs

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "BirthdayMandatory")]
    [Display(Name = "Birthday", ResourceType = typeof(Resources.Resources))]
    [MinimumAge(MinAge = 16, ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "MinimumAgeMessage")]
    [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birthday { get; set; }

Page.cshtml

            <div class="form-group">
                @Html.LabelFor(model => model.Birthday, new { @class = "control-label" })
                @Html.TextBoxFor(model => model.Birthday, "{0:dd/MM/yyyy}", new { @class = "form-control", @name = "date", placeholder = "dd/mm/yyyy" })
                @Html.ValidationMessageFor(model => model.Birthday)
            </div>

这里是MinimumAgeAttribute

public class MinimumAgeAttribute : ValidationAttribute, IClientValidatable
{

    public int MinAge { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //THIS IS FOR SERVER SIDE VALIDATION

        // if value not supplied then no error return
        if (value == null)
        {
            return null;
        }

        int age = 0;
        age = DateTime.Now.Year - Convert.ToDateTime(value).Year;
        if (age >= MinAge)
        {
            return null; // Validation success
        }
        else
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            // error 
        }
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        //THIS IS FOR SET VALIDATION RULES CLIENT SIDE

        var rule = new ModelClientValidationRule()
        {
            ValidationType = "minimumage",
            ErrorMessage = FormatErrorMessage(metadata.DisplayName)
        };

        rule.ValidationParameters["minage"] = MinAge;
        yield return rule;
    }
}

然后,输入大于12的日期时,验证错误始终显示Birthday must be a date20/02/1991

我已经通过以下方式修复了它:

    //to correct dd/mm/yyyy bug in asp validation
    $(function () {
        $.validator.methods.date = function (value, element) {
            return this.optional(element) || moment(value, "DD/MM/YYYY", true).isValid();
        }
    });

但是最低年龄验证无效。

请帮助

1 个答案:

答案 0 :(得分:0)

搜索了多个小时后,我找不到令人满意的答案。

我最终使用了JavaScript验证:

  1. ModelView数据类型更改为字符串而不是日期,然后进行相应的转换。

  2. Fire自定义javascript验证方法

            <div class="form-group">
                @Html.LabelFor(model => model.Birthday, new { @class = "control-label" })
                @Html.TextBoxFor(model => model.Birthday, new { id = "birthday-input-txt", @class = "form-control", type = "text", placeholder = "dd/mm/yyyy", onblur = "ValidateDOB()" })
                @Html.ValidationMessageFor(model => model.Birthday, "", new { id = "birthday-error-message" })
            </div>
    

Javascript:

    function ValidateDOB() {
        var lblError = $("#birthday-error-message");
        //Get the date from the TextBox.
        var dateString = $("#birthday-input-txt").val();
        var regex = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;

        //also fire existing validation
        $("#update-profile-form").valid();

        //Check whether valid dd/MM/yyyy Date Format.
        if (regex.test(dateString)) {
            var parts = dateString.split("/");
            var dtDOB = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
            var dtCurrent = new Date();
            lblError.html("@Resources.Resources.MinimumAgeMessage");
            if (dtCurrent.getFullYear() - dtDOB.getFullYear() < 16) {
                lblError.addClass('field-validation-error').removeClass('field-validation-valid');
                return false;
            }

            if (dtCurrent.getFullYear() - dtDOB.getFullYear() == 16) {

                //CD: 11/06/2018 and DB: 15/07/2000. Will turned 16 on 15/07/2018.
                if (dtCurrent.getMonth() < dtDOB.getMonth()) {
                    lblError.addClass('field-validation-error').removeClass('field-validation-valid');
                    return false;
                }
                if (dtCurrent.getMonth() == dtDOB.getMonth()) {
                    //CD: 11/06/2018 and DB: 15/06/2000. Will turned 18 on 15/06/2018.
                    if (dtCurrent.getDate() < dtDOB.getDate()) {
                        lblError.addClass('field-validation-error').removeClass('field-validation-valid');
                        return false;
                    }
                }
            }
            //lblError.innerHTML = "";
            lblError.addClass('field-validation-valid').removeClass('field-validation-error');
            return true;
        } else {
            lblError.html("@Resources.Resources.WrongDateFormatMsg")
            lblError.addClass('field-validation-error').removeClass('field-validation-valid');
            return false;
        }
    }

此外,在提交之前将其触发:

<input type="submit" value="@Resources.Resources.Save" class="btn" onclick="return ValidateDOB()" />

此链接有很大帮助:https://www.aspsnippets.com/Articles/Date-of-Birth-Age-Validation-in-JavaScript.aspx