user576785
user576785

Reputation: 19

set a dateformat dd/mm/yy for range validator

I have a range validator to validate a textbox for birthday. i must ensure that a student must be above 21 to register with us. i set "31/12/1993" format (dd/mm/yy). but it cannot run the website as in my database is set to this (mm/dd/yy) format. how can i solve this without changing my database format? so that it can function for everyone.

thx.

Upvotes: 1

Views: 2220

Answers (2)

Sukhjeevan
Sukhjeevan

Reputation: 3156

Check it out-->

string sBDate = "31/12/1993";
DateTime datBirthDay = ValidateDate(sBDate);

DateTime datToday = new DateTime();
datToday = DateTime.Today.Date;

if (datToday.Year - datBirthDay.Year < 21)
{ 
    //Error message:-You must be above 21.
}

public DateTime ValidateDate(string strInputDate)
{
    DateTime datReturnDate = new DateTime();
    DateTime datTempDate = new DateTime();

    datTempDate = DateTime.Parse("1/1/1900");
    string[] strArrDateFormat = {
    "dd.MM.yy",
    "dd.MM.yyyy",
    "dd-MM-yy",
    "dd-MM-yyyy",
    "dd/MM/yy",
    "dd/MM/yyyy",
    "dd MMM yy",
    "MMM yy",
    "MMM yyyy",
    "MMM-yy",
    "MMM-yyyy",
    "MMMM yyyy",
    "d MMMM yyyy",
    "dd MMMM yyyy",
    "MMMM yy",
    "d/M/yy"
};

    if (DateTime.TryParseExact(strInputDate, strArrDateFormat, null, DateTimeStyles.None, out datReturnDate))
    {
        //Format matched
    }
    else
    {
        datReturnDate = datTempDate;
    }

    return datReturnDate;
}

Upvotes: 0

Emond
Emond

Reputation: 50672

Use a DateTime in C# and have ADO translate it to a Database specific type (what db are you using?) and pass it as a parameter. NOT as a string.

Also, to prevent errors, use a calender for user input.

Alternative: clearly indicate the required format.

You could retrieve the user's browser languages:

string[] languages = Request.UserLanguages;

Then create a CultureInfo with this string (the split might be needed):

CultureInfo ci = new CultureInfo(languages[0].Split(";")[0]);

and get the corresponding dateformat:

string datePattern = ci.DateTimeFormat.ShortDatePattern

Then use the pattern to parse the user input.

DateTime.TryParseExact(userInput, datePattern, ...

Upvotes: 2

Related Questions