bgs264
bgs264

Reputation: 4642

RegularExpressionValidator returning false for a valid input

I want to validate input into a textbox, so it must contain six (optionally seven) characters within square brackets. This can appear anywhere within the string, not the entire string itself. Example valid input: Hello World [XX1111]

I have come up with the following Regular Expression: \[.......?\]

However, this expression does not seem to work within a RegularExpressionValidator:

<asp:TextBox ID="txtTest" runat="server" />
<asp:RegularExpressionValidator ID="rfvTest" runat="server" ControlToValidate="txtTest" 
    ValidationExpression="\[.......?\]" ErrorMessage="Enter in the right format...">Enter in the right format</asp:RegularExpressionValidator>
<asp:Button ID="btnTest" runat="server" Text="test" />

Even valid input, causes the error to display, and the .IsValid property of the Page to be false.

Interestingly, the following C# code will cause match to be true (with text of Hello [XX1111])

            Regex r = new Regex(rfvTest.ValidationExpression);
            bool match = r.IsMatch(txtTest.Text);

So: What's up here. I believe the expression itself to be correct, it validates as expected using the Regex class, but the RegularExpressionValidator will not validate the input.

Upvotes: 0

Views: 1334

Answers (1)

fge
fge

Reputation: 121710

The problem appears to be that this control unfortunately adds beginning and end of input anchors to the regular expression you submit (and does not document that it does so)...

Which means you must surround your regex with, yes, .* on both sides. Could be viewed as a bug...

Upvotes: 1

Related Questions