Hi
I want the user to only type letters (a-z simple or capital) in the Name textbox.If the user types any other character(like numbers or commas,semicolons) I want to show a message.How can I check for it(in C#)?
Thnx in Advance

Dani AI

Generated

Quick note: 's approach (use a regex to allow letters only) is a fine start for simple cases. A few practical tips and safer alternatives follow so the validation works well in real apps and for non‑ASCII names.

Use Unicode letter classes and allow common name characters (spaces, apostrophes, hyphens). This avoids rejecting names with accents or combined marks. Example server-side C# check:

using System.Text.RegularExpressions;

var name = txtName.Text?.Trim();
if (string.IsNullOrWhiteSpace(name) || !Regex.IsMatch(name, @"^[\p{L}\p{M}'\- ]+$"))
{
    // production: set a validation error or return a validation result
}

If the project is ASP.NET, prefer framework validators so you get client-side behavior plus server-side safety. For MVC/models use a DataAnnotation:

[RegularExpression(@"^[\p{L}\p{M}'\- ]+$", ErrorMessage = "Use letters, spaces, apostrophes or hyphens only.")]
public string Name { get; set; }

Cautions and troubleshooting:

  • Do not rely on client-side checks alone. Always validate on the server.
  • If using RegexOptions.ECMAScript, Unicode categories (\p{L}) are not supported; remove that option.
  • HTML5 input pattern support for Unicode character classes is spotty across browsers; test if you use it.
  • Be permissive: many real names include spaces, hyphens, apostrophes, and diacritics. Rejecting them will frustrate users.

This complements 's answer and avoids surprising rejects for legitimate names.

Recommended Answers

All 2 Replies

Place this below code into button click if you want to check or to textchanged event.

bool isStrictMatch = false;
            string patternStrict = @"^([a-zA-Z]+)$";
            Regex reStrict = new Regex(patternStrict);
            if (txtSecond.Text.Trim() != string.Empty)
            {
                isStrictMatch = reStrict.IsMatch(txtSecond.Text.Trim());
                if (!isStrictMatch)
                    MessageBox.Show("Please use alphabetics", "Validation", MessageBoxButtons.OK);
            }

Hi
thnx it wrks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.