1

I am currently trying to validate a textbox, so only letters (a-Z) can be entered, with the use of TryParseExact.

I have a code to check a time, although could someone demonstrate how this could be done with letters only.

My code is as follows:

private void textBox2_Validating(object sender, CancelEventArgs e)
{
    DateTime dateEntered;

    if (DateTime.TryParseExact(textBox2.Text, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))
    {

    }
    else
    {
        MessageBox.Show("You need to enter valid 24 hour time");
    }
}
1
  • What do you mean with letters only? No numbers? No spaces or punctuation? Commented Jun 20, 2011 at 17:07

2 Answers 2

3

This checks if all characters in a string s are a letter:

bool result = s.All(ch => char.IsLetter(ch));

See also: Char.IsLetter Method (MSDN)

If you want to accept only ASCII letters (i.e. a-z and A-Z):

bool result = s.All(ch => (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'));
Sign up to request clarification or add additional context in comments.

3 Comments

How could I implement this into my current method?
@Dan: Are you asking how to combine a boolean expression and if?
0

You should not use any try-parse method because checking if a string only contains a-Z chars is not the same as parsing a date or a number.

I think you can use regular expressions to validate the input.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.