Sponsored Ad

Monday, March 22, 2010

First Name and Last Name Validation in C# using Regex

      

This is custom utility to validate first name and last name  using regular expressions.

 

It takes string as a input parameter and return the true and false value for valid and invalid string.

remember to user namespace for regular expression using System.Text.RegularExpressions

 

using System.Text.RegularExpressions;

       /// <summary>
       /// Validate firstname and lastname.
       /// </summary>
       public static bool IsValidName(string strToCheck)
       {
           return Regex.IsMatch(strToCheck, "^[a-zA-Z ]+$");
       }

3 comments:

  1. This is good stuff, but my question would be how would modify the expression to allow for a hyphenated last name?

    ReplyDelete
  2. You can use \- to add hyphen in last name.
    Regex.IsMatch(strToCheck, "^[a-zA-Z\- ]+$");

    Please note that you need to write two different regular expressions if you want hyphen in only last name.

    ReplyDelete
  3. Thanks, Raj! I look forward to testing that out.

    ReplyDelete

Sponsored Ad

Website Update

Followers