Best way to validate data?

CustomValidator Control

Page 1 of 1

2 Replies - 2038 Views - Last Post: 07 June 2010 - 04:05 PM Rate Topic: -----

#1 EvLSnoopY  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 93
  • Joined: 24-November 09

Best way to validate data?

Posted 05 June 2010 - 07:08 AM

I'm reading through an ASP.Net book and all of the code is in VB. The code for validating the date the user enters in is:
Sub ServerValidation (source As object, args As ServerValidateEventArgs)
    args.IsValid = IsDate(args.Value);
End Sub


I wanted to translate the preceding code to C# and came up with this:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    try
    {
        DateTime date = DateTime.Parse(args.Value);
        args.IsValid = true;
    }
    catch (FormatException)
    {
        args.IsValid = false;
    }
}


My question is, is there a better way of coding this in C#?

Is This A Good Question/Topic? 0
  • +

Replies To: Best way to validate data?

#2 Frinavale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 203
  • View blog
  • Posts: 776
  • Joined: 03-June 10

Re: Best way to validate data?

Posted 07 June 2010 - 10:06 AM

You could use the DateTime.TryParse() method instead. This method does not throw any exceptions when it tries to convert/parse the string into a DateTime.

Please note that some malicious attacks (like the buffer over flow attack)take advantage of exceptions: In this type of attack the malicious code modifies the application pointer so that after an exception is thrown it returns to their code instead of yours.

With this in mind, I would chose the TryParse method :)

Not only that but you don't have the clutter of Try-catch blocks in your code...it's replaced by an if-statement :)

-Frinny
Was This Post Helpful? 1
  • +
  • -

#3 EvLSnoopY  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 93
  • Joined: 24-November 09

Re: Best way to validate data?

Posted 07 June 2010 - 04:05 PM

Man! thanks a lot Frinavale. When I posted this up I was not in the right state of mind (I was beyond sleepy). This is exactly what I was looking for, and I remember saying to myself "How come the DateTime class doesn't have a TryParse() Method like int does?" lol I was so stupid...It didn't occur to me that I should just type it in and see if it was actually a valid method of the DateTime class. Haha thanks once again bro. Rep++
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1