regex - check if a string contains only alphabets c#

How to validate that input string contains only alphabets, validating that textbox contains only alphabets (letter), so here is some of the ways for doing such task.
char have a property named isLetter which is for checking if character is a letter or not, or you can check by the regular expression  or you can validate your textbox through regular expression validator in asp.net.

Following code demonstrating the various ways of implementation.

Code to validate that string contains only letters through char isLetter property.

public bool IsAlphabets(string inputString)
{
      if (string.IsNullOrEmpty(inputString))
          return false;

      for (int i = 0; i < inputString.Length; i++)
          if (!char.IsLetter(inputString[i]))
              return false;
      return true;
}


Validate that string contains only alphabets (letters) as well as space character through regular expression

public bool IsAlphabets(string inputString)
{
    Regex r = new Regex("^[a-zA-Z ]+$");
    if (r.IsMatch(inputString))
        return true;
    else
        return false;
}


verifying that textbox text contains only alphabets as well as space character through Regular Expression Validator in asp.net (validation controls),it checks server side and client both.

<asp:TextBox ID="txtName" runat="server" ></asp:TextBox>

<asp:RegularExpressionValidator ID="REValphaOnly" runat="server" ErrorMessage="Please enter only alphabets." ControlToValidate="txtName" ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>



Popular Posts