Date Check - StartDate, EndDate MVC

I need to do a check on StartDate and EndDate

Validations:

  • StartDate must be set to less than or equal to Endate.
  • The EndDate value must be greater than or equal to the start value.

So far my code is:

an object:

    [DisplayName("Effective Start Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
    public DateTime EffectiveStartDate { get; set; }

    [DisplayName("Effective End Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
    public DateTime EffectiveEndDate { get; set; }

View:

   </tr>  
          <tr>
            <td class="lables"><%= Html.LabelFor(model => model.EffectiveEndDate)%></td>
            <td class="data" id = "endDate"><%= Html.EditorFor(model => model.EffectiveEndDate)%>
            <%= Html.ValidationMessageFor(model => model.EffectiveEndDate)%></td>
        </tr>  
          <tr>
            <td class="lables"><%= Html.LabelFor(model => model.ErrorCheckEnabled)%></td>
            <td class="data" ><%= Html.TextAreaFor(model => model.ErrorCheckEnabled)%>
             <%= Html.ValidationMessageFor(model => model.EffectiveEndDate)%></td>
        </tr> 

How do I get tested. Should I do on the client site on

$("#frm").validate

[or]

???

+3
source share
2 answers

: , javascript, . , UX . .

, ValidationAttribute. :

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EndDateAttribute : ValidationAttribute
{
    public EndDateAttribute(DateTime endDate)
    {
        EndDate = endDate;
    }

    public DateTime EndDate { get; set; }

    public override bool IsValid(object value)
    {
        if (value == null)
            return false;

        DateTime val;
        try
        {
            val = (DateTime)value;
        }
        catch (InvalidCastException)
        {
            return false;
        }

        if (val >= EndDate)
            return false;

        return true;
    }

}

, , , StartDate.

: . ().

[DisplayName("Effective Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
[StartDate(DateTime.Now)]
public DateTime EffectiveStartDate { get; set; }

[DisplayName("Effective End Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
[EndDate(new DateTime(2011, 9, 24)]
public DateTime EffectiveEndDate { get; set; }
+1

?

0

Source: https://habr.com/ru/post/1778654/


All Articles