Monday, February 13, 2012

C# : Some basic validation




Doing some basic validation and I found these to be useful:

Check for mandatory fields:
if (String.IsNullOrEmpty (xxx)) … error

Field must be numeric only:
int number;
bool result = Int32.TryParse (xxx, out number);
if (!result) … error

Valid date format:
DateTime date;
bool result = DateTime.TryParse (xxx, out date);
if (!result) … error

Valid email format:
bool result = Regex.IsMatch(xxx, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)
(([\w-]+\.)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$");
if (!result) … error

Enjoy!

6 comments:

  1. Nice post these are some basic thing but the thing is few of then are not known by me,
    Thanks for sharing

    ReplyDelete
  2. Hi...

    Great blog every thing is new for me, i have get good stuff from this.
    Thanks

    ReplyDelete
  3. Every thing is good explained i get the thing which i want from this post.

    ReplyDelete
  4. This is something new to get into for me, I have just started with C# so some concepts are not understood to me. Everything upto valid format was fine but didn't understand what exactly Regex.IsMatch does.

    ReplyDelete
  5. You can Google the Regex C# stuff but it's just searching the string for a valid email address format i.e. some characters then a "@" then some characters then a "." etc.

    ReplyDelete
  6. This is an excellent component for verifying email addresses:
    http://www.kellermansoftware.com/p-37-net-email-validation.aspx

    ReplyDelete