Monday, March 26, 2012

Validating datatype in DetailsView EditItemTemplate

Hi

Im using the CompareValidator to validate the datatype of date input into a DetailsView EditItemTemplate. The field can be empty, or must be a date datatype which must be formatted as a US style date.

However, I get the following error: "The value '' of the ValueToCompare property of 'valDisplayFrom' cannot be converted to type 'Date'."
I understand that it is failing as the page loads, as the bound text is a string, rather than an expected datetime. Im not sure how to fix this, or if its actually possible. However, its preferable to validate user inputs before they submit the whole DetailsView "form".

<EditItemTemplate>
<asp:TextBoxID="txtDisplayFrom"runat="server"Text='<%# Bind("DisplayFrom", "{0:MMM/dd/yyyy}") %>'></asp:TextBox>
<asp:CompareValidatorID="valDisplayFrom"runat="server"ControlToValidate="txtDisplayFrom"
Type="Date"ErrorMessage="Please enter valid Date"></asp:CompareValidator>
</EditItemTemplate>

Any help greatly appreciated.

Thanks

Penny

Hi Penny,

You have to make sure if DisplayForm column is null or '' before convert it to 'date' type.

You can create DisplayFormat method if DisplayForm is not null or '' convert it to 'date' type.

<%# DisplayFormat(Eval("DisplayFrom")) %>

No comments:

Post a Comment