Validator throwing error
I have the following RegularExpressionValidator on one of my pages:
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="InKindTextBox"
ErrorMessage="The value entered for 'Cash' must be in a number format. Examples: 500.00, 500, $500, $50,000 or $500.00"
ValidationExpression="(?n:(^\$?(?!0,?\d)\d{1,3}(?=(?<1>,)|(?<1>))(开发者_高级运维\k<1>\d{3})*(\.\d\d)?)$)" >
But when it tries to validate it throws the error below from one of my dynamic JS pages.
When I run this regex through regex texter it works fine. Am i doing something wrong here?
I think your regex is too complicated anyway. I'd use something simpler like
^[1-9]\d*(\.\d*)?$
That says no leading 0, at least one number before the decimal point, and an optional decimal point followed by more numbers.
Edit
^\$?([1-9]\d?\d?((,\d{3})*|(\d{3})*)|0?)(\.\d*)?$
To test it
var r = /^\$?([1-9]\d?\d?((,\d{3})*|(\d{3})*)|0?)(\.\d*)?$/;
var shouldMatch = ["$30,000.00", "30,000.00", "9,000.00", "9000", "1", ".12"];
var shouldntMatch = ["30,000000.00", "1.00c", "19,00.00", "$30,00"];
function test1() {
for (var i in shouldMatch) {
if (!r.exec(shouldMatch[i])) {
alert(shouldMatch[i]);
return;
}
}
}
function test2() {
for (var i in shouldntMatch) {
if (r.exec(shouldntMatch[i])) {
alert(shouldntMatch[i]);
return;
}
}
}
test1();
test2();
JavaScript uses a different regexp syntax than .NET. See, for example, this page.
Quote from MSDN's RegularExpressionValidator page:
The regular-expression validation implementation is slightly different on the client than on the server. On the client, JScript regular-expression syntax is used. On the server, System.Text.RegularExpressions.Regex syntax is used. Since JScript regular expression syntax is a subset of System.Text.RegularExpressions.Regex syntax, it is recommended that JScript regular-expression syntax be used in order to yield the same results on both the client and the server.
Update: A thorough comparison of regular expression flavors across many languages including .NET and JavaScript can be found here.
Update 2: Below is a regex that should validate currency input using jScript compliant regex:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="CashTextBox" ValidationGroup="vld_Insert"
ErrorMessage="The value entered for 'Cash' must be in a number format. Examples: 5000, 5000.00, 5,000 or $5,000.00"
ValidationExpression="^\s*\$?\s*(?!\d{4,},)(\d|\d{1,3},(?=\d{3})(?!\d{4}))*(\.\d{1,2})?\s*$">
精彩评论