PandaNinja PandaNinja - 5 months ago 9
Javascript Question

How to modify Validation Regular Expression for form COMMA user input in ASP.net?

Numbers with 4 or more digits require a comma in this form. I need to remove this requirement but allow for commas if the user inputs it.

<asp:TextBox ID="txtCharges" CssClass="input" placeholder="Fee" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvCharges" runat="server" ControlToValidate="txtCharges" ValidationGroup="SaveClaim"
ErrorMessage="Fee is Required" ForeColor="Red" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexpName" runat="server" ErrorMessage="Fee Format 9,999.99 or 9999"
ControlToValidate="txtCharges" ValidationExpression="^\d{1,3}(?:,\d{3})?(?:\.\d{2})?$" ValidationGroup="SaveClaim" ForeColor="Red" />

Answer

In order to make any character / group optional in RegEx, you have two options:

  1. Use {0,1} to let it know that the character preceding can max occur 1 time.
  2. Use ? This metacharacter allows you to match either zero or one of the preceding character or group

In your case, you need to change your expression in the below way to let browser indicate your , is optional.

^\d{1,3}(?:,?\d{3})?(?:\.\d{2})?$