validate age according to date of birth using mode

2020-02-29 10:03发布

I have registration form and its contain date of birth field.

Using calender date picker its input the value to this field.

these are the steps to insert value for this field

step 1

enter image description here

step 2

enter image description here

step 3

enter image description here

so its taking values in dd/MM/yyyy format

This is appearance of date of birth field in my model class

[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }

This is appearance of date of birth field in my view file

   <div class="form-group"> 
   <div class="editor-label">
        @Html.LabelFor(model => model.Date_of_Birth)
        @Html.Label("*", new { id="star" , @class = "requiredFiledCol" })
   </div>
   <div class="editor-field">
        @Html.TextBoxFor(model => model.Date_of_Birth, "{0:dd/MM/yyyy}", new { @class = "form-control datepicker", placeholder = "DD/MM/YYYY" , maxlength="100" })
        @Html.ValidationMessageFor(model => model.Date_of_Birth)
    </div>
    </div>

I want to do client side validation for data of birth field . show error message when input filed is not in this range 100>Age>18

whats the approach I should take ?

3条回答
Melony?
2楼-- · 2020-02-29 10:27

I've improved on Walter's answer regarding making your own custom validation. I've added better error message support. This will allow a better default error message and also allow you to enter your own with better string.Format support. I've also updated the naming schemes. For instance you should add date to the beginning so that you and other developers know that this validation can only be used with DateTime variables similar to how the base StringLengthAttribute is named for strings.

public class DateMinimumAgeAttribute : ValidationAttribute
{
    public DateMinimumAgeAttribute(int minimumAge)
    {
        MinimumAge = minimumAge;
        ErrorMessage = "{0} must be someone at least {1} years of age";
    }

    public override bool IsValid(object value)
    {
        DateTime date;
        if ((value != null && DateTime.TryParse(value.ToString(), out date)))
        {
            return date.AddYears(MinimumAge) < DateTime.Now;
        }

        return false;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, MinimumAge);
    }

    public int MinimumAge { get; }
}


[DateMinimumAge(18, ErrorMessage="{0} must be someone at least {1} years of age")]
[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }
查看更多
Luminary・发光体
3楼-- · 2020-02-29 10:28

Create an id for @Html.ValidationMessageFor and @Html.TextBoxFor, then use javascript to validate it. In your view do something like:

@section scripts{
    <script>
      $(function () {
         if (document.getElementById("yourTextBoxID").value < 18){
             document.getElementById("yourValidationMessageID").value = "Can't be less than 18 years old :("
            }
       });
    </script>
}
查看更多
时光不老,我们不散
4楼-- · 2020-02-29 10:43

Well since you are already using data annotations why not make your own. do this:

create a class in an dll that you use or make a new one and at a minimum add the following code to it

public class MinimumAgeAttribute: ValidationAttribute
{
    int _minimumAge;

    public MinimumAgeAttribute(int minimumAge)
    {
      _minimumAge = minimumAge;
    }

    public override bool IsValid(object value)
    {
        DateTime date;
        if (DateTime.TryParse(value.ToString(),out date))
        {
            return date.AddYears(_minimumAge) < DateTime.Now;
        }

        return false;
    }
}

then in your view model do this:

[MinimumAge(18)]
[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }

or your web page you will have no issues as the framework(s) you use will pick it up. Without changing the ErrorMessage property in your class you will get something like

The field "{0}" is not valid.

The {0} is replaced by the property name or display name attribute that you gave the property in your model.

Hope it works for you.

Walter ps: make sure in the controller you do

if (ModelState.IsValid)
{
 ....
}
查看更多
登录 后发表回答