jquirante
jquirante

Reputation: 33

C#: Validating textbox using regular expressions

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

Answers (3)

mikesigs
mikesigs

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.

  • 10.00 PASS
  • 1.00 PASS
  • 1.1 PASS
  • 1 PASS
  • 1. FAIL
  • 10,00 FAIL

Upvotes: 0

Jonathan Michaels
Jonathan Michaels

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));
        }
   }
}
  • $0.99 True
  • True $1099999.00
  • True $10.25
  • True $90,999.99
  • False $1,990999.99

Upvotes: 0

Jonathan Wood
Jonathan Wood

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

Related Questions