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:

Error2908 win 7 said...

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

Error 1316 said...

Hi...

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

Uniblue said...

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

Gavin Tracey said...

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.

nzpcmad said...

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.

Asava Samuel said...

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