0

I have a SmallDateTime field in my Sql Server 2008 database to store users Birthdays.

On my 'Edit Profile' web page, I have a standard textbox which I want to bind the 'Birthday' date to (excluding the time as this is not required). At present I am binding to the textbox but it is rendering the full Date and Time.

In addition, when the user updates their profile, I want to be able to validate the Birthday textbox, ensuring that the value specified complies to dd/mm/yyyy, and any deviation from that is highlighted via my existing validation summary on the page.

How do I go about:

a) configuring the Birthday property in my ViewModel to display in dd/mm/yyyy format (excluding the time).

b) validate Birthday (based on dd/mm/yyyy format) when the user submits the form?

3 Answers 3

1
[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
public DateTime DateOfBirth { get; set; }

This should give you the automatic formatting on the field (without you having to manually do it) and also the validation.

Sign up to request clarification or add additional context in comments.

Comments

0

I usually use a string property paired with the DateTime object, something like

public string MyDateStr 
{
   get 
   {
       return MyDateDate == null ? "" : MyDateDate.ToShortDateString();
   }
   set
   {
      // Usually a tryParse for the string value
   }
}

I know that is not the canonical way, but up to now, is the fastest I've found.

HTH

M.

EDIT: for the validation stuff see this:other question on SO

Comments

0

a) you can use .ToShortDateString to render your datetime without time. Format still depends on globalization defaults.

b) to validate, you could do it with Data Annotations on your model like this:

[DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
public DateTime Birthday { get; set; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.