I need to do validation on StartDate and EndDate
Validations:
So far my code:
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 should I go with validation. Should I do on client site on
$("#frm").validate
[or]
???
This must be said: You should always do a server-side validation, as the user can turn off javascript and thus your validation won't be applied. But I recommend making client-side validation as well so the UX will be nicer. Server-side and client-side validation can easily exist simultaneously.
For server-side you can easily create your own validation attribute by deriving from the ValidationAttribute class. Look at this example:
[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;
}
}
You can probably figure out how to make StartDate.
UPDATE: Using this is quite simple. You just have to apply it to your properties as any other (validation) attribute. For example
[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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With