Reputation: 33
I am looking to validate a text box. The text box is used so that the user can input a clients rate of pay. eg. 8.40, 10.50, 24.80. I want to validate it and I have read that using regular expressions would be the faster and easier way to go. Problem is I am still not familiar with how the characters are being used within the brackets. Any help is greatly appreciated. Thanks!
Upvotes: 2
Views: 6988
Reputation: 11380
<asp:TextBox ID="txtPayRate" runat="server" />
<asp:RegularExpressionValidator
ID="revPayRate"
ControlToValidate="txtPayRate"
ValidationExpression="\d+(\.\d{1,2})?"
ErrorMessage="Message to display in ValidationSummary control"
Text="Message to display in control"
runat="server" >
</asp: RegularExpressionValidator>
The regular expression can be translated as follows:
One or more digits - OR - One or more digits followed by a decimal and one or two digits.
\d+ Any digit, one or more repetitions
(.\d{1,2})? A numbered capture group, zero or one repetitions. Broken down as follows:
\. Literal .
\d{1,2} Any digit, between 1 and 2 repetitions
This will only work for English currencies though. Here's a few examples of what will pass/fail.
Upvotes: 0
Reputation: 68
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
public class MainClass{
public static void Main(){
Regex moneyR = new Regex(@"\$(((\d{1,3},)+\d{3})|\d+)\.\d{2}");
string[] money = new string[] { "$0.99",
"$1099999.00",
"$10.25",
"$90,999.99",
"$1,990,999.99",
"$1,999999.99" };
foreach (string m in money){
Console.WriteLine(m);
Console.WriteLine(moneyR.IsMatch(m));
}
}
}
Upvotes: 0
Reputation: 67193
Well, I could ask several questions about what exactly constitutes valid input. But here's an alternate approach:
double dbl;
if (!double.TryParse(Text1.Text, out dbl))
MessageBox.Show("Invalid value entered!");
Upvotes: 4