Textbox input validation
Hi
here i'm trying to enter some text into textbox but my problem is it accepts any data what i want is the input text should starts with alphabetics (a to z or A to Z) only. How can i do this? Can anybody give me a simple code to do this
Thanx - Nagu
[265 byte] By [
Nagu] at [2007-12-21]
In the TextChanged event of your textbox, use a code that will find all the word in it and see if they start with what you want.
Something like this :
public void textbox1TextChanged(object sender, RoutedEventArgs e)
{
foreach(string word in textbox1.Text.Split(' '))
{
// Use a regular expression to test word
}
}
Here is an example but not the best one: to fit all the possible scenarios, you should use a regular expression:
string
s = "Hello 12rld"; foreach(string word in s.Split(' ')) {
char c = Convert.ToChar( word.Substring(0, 1)); int a; if ( Int32.TryParse(c.ToString(), out a)) {
Console.WriteLine("Start with number"); }
else {
Console.WriteLine("Ok"); }
}
HTH
Calling Split on every TextChanged event is needless overhead, just scan the string straight out. Convert is also unneccesary, as strings expose an enumerator over their characters. And the Int32 parsing...why? :)
void TextBox_TextChanged(object sender, RoutedEventArgs e)
{
string test = (sender as TextBox).Text;
foreach(char c in test)
{
if((c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') || c == ' ')
{
// ok
}
else
{
// not okay
}
}
}
To prevent a bad character from ever showing up in the text box, I think you can process the PreviewTextChanged event instead and, if the character is "bad," set e.Handled = true to prevent it from being processed further.
Ah, I see why you would be using Int32.Parse there, given the OP's problem...but it's still unnecessary. It becomes unnecessary to scan the entire string, even. To check if the input string starts with an alpha, just check the 0th position of the string to see if it falls in [a-zA-Z ]:
if(test[0] == "...")
Yeah, you're right: what I said was just a possible idea where to start.
It coule also be interesting to use StartWith, as he wants to check if only the beginning of the text is a number.