How to validate user input?

Ramy Mahrous 0 Tallied Votes 366 Views Share

Here's I wrote some code to validate user input without using if\else statements.
I believe in scalability is the most important aspect in our problems solution. Let's say we are required to permit only numerics in some text boxes; we shouldn't develop something like that if(((e.KeyChar < '0' || e.KeyChar >'9')) we HAVE to use Regular Expression Regex class and match string with pattern (when something changes go and change patterns) you can set it in App.Config file which means you won't open the source code again.

Common Regular Expression Patterns
http://en.csharp-online.net/CSharp_Regular_Expression_Recipes—Using_Common_Patterns

//This code developed by Ramy Mahrous 
//ramyamahrous@hotmail.com
//Its contents is provided "as is", without warranty.

/// <summary>
/// Validates if text matches the pattern
/// </summary>
/// <param name="pattern">Regular experssion pattern</param>
/// <param name="text">Text to be validated</param>
/// <param name="options">Regular experssion options</param>
/// <returns>True if matches, otherwise false</returns>
public bool IsValid(string pattern, string text, RegexOptions options)
{
return System.Text.RegularExpressions.Regex.IsMatch(text, pattern, options);
}

///Some usage

///To validate user input when submitting data
private void SubmitButton_Click(object sender, EventArgs e)
{
if(IsValid(PatternTextBox.Text, textBox2.Text, 
RegexOptions.Multiline | RegexOptions.Compiled))
{
MessageBox.Show("Your input is correct");
}
else
{
MessageBox.Show("Your input is not correct");
}
}

///To validate user input while user type some text
private void textBox2_TextChanged(object sender, EventArgs e)
{
if(IsValid(PatternTextBox.Text, textBox2.Text, 
RegexOptions.Multiline | RegexOptions.Compiled))
{
MessageBox.Show("Your input is correct");
}
else
{
MessageBox.Show("Your input is not correct");
}            
}
ddanbe 2,724 Professional Procrastinator Featured Poster

Nice snippet Ramy.
The only thing I don't like is the MessageBox that says everything is correct! Only show a MessageBox if something is wrong. But I suppose you did it here for debugging (and other...) purposes. Gave you 4 stars.

Ramy Mahrous 401 Postaholic Featured Poster

Yes, I agree message boxes headache but in some cases it should be used, but in such error some alternatives better. Thanks Danny :)

ADias-Jayasinha 0 Newbie Poster

Wouldn't it be better to prevent anything other than digits being entered into the text box from the outset? When any key other than the numerics are pressed and the text box does not accept it you know that you have entered something wrong. This can dispense with the message box.

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.