w0051977
w0051977

Reputation: 15787

Validate text in maskedTextBox

Say I have three strings like this (entered into three masked text boxes):

string string1="£1,252,52";
string string2="£1,   .52";
string string3="£2, 52.52;

The second and third string are invalid. How can I identify string2 as being invalid. I have to say:

If there is a blank space after a number then the string is invalid i.e.

if (blank space after number)
return true;
else
return false;

I have done this in SQL before using the LIKE statement. However, I cannot figure out how to do it in C#.

Upvotes: 0

Views: 1256

Answers (2)

Mohd Ismail Siddiqui
Mohd Ismail Siddiqui

Reputation: 678

You can use Regular expression to validate your input. like this:

System.Windows.Forms.TextBox textbox1 =  new System.Windows.Forms.TextBox(); 
            textbox1.Text = "£1,252,52";
            string pattern = @"^\£?(\d{1,3},?(\d{3},?)*\d{0,3}(.\d{0,3})?|\d{1,3}(.\d{2})?)$";
            if (System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, pattern))
            {
                //if string matched
            }
            else
            {
                //if not matched
            }

Upvotes: 1

degant
degant

Reputation: 4981

You can validate your text like this:

string string1 = "£1,252.52";

var pattern = @"^\£\d{1,3}(,\d{3})*(\.)(\d+)";
var regex = new Regex(pattern);

return regex.IsMatch(string1)

The regex ^\£\d{1,3}(,\d{3})*(\.)(\d+) validates numbers in occordance with your template of £999,999.00. It makes sure the input starts with a £, contains commas after every 3 characters and has a decimal space.

Test: Regexstorm

Upvotes: 0

Related Questions