I have a requirement to show numbers in text boxes with comma-separator formatting for thousands. Each text box is like this:
<asp:TextBox ID="txtNumber" MaxLength="16" runat="server" onfocus="unFormatTextBox(this);" onblur="formatTextBox(this);" />
When the page is drawn, the number is formatted server-side, so that 1000.50 will become 1,000.50 and this is set as the text box value.
When the user clicks into the text box - for ease of editing - the commas are removed.
function unFormatTextBox(elementId) {
// removes commas on focus
var num = elementId.value;
elementId.value = num.replaceAll(',', '');
}
When the user clicks elsewhere and the text box loses focus, the entry is reformatted and the commas are reinserted..
function formatTextBox(elementId) {
// add commas on mouseout
var num = elementId.value;
var parts = num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
elementId.value = parts.join(".");
}
This works perfectly. However it's conflicting with the RegularExpressionValidator..
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNumber" ErrorMessage="" ValidationExpression="^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?$">*</asp:RegularExpressionValidator>
So the user keys:
1500
When the text box loses focus, e.g. they click to the next one, that gets reformatted as:
1,500
The problem: The Validator then fires and shows the entry as incorrect even though it ought to be fine. The Validator should allow that entry with the comma (I'm then removing that server-side before dealing with the submitted value).
However if the user then clicks Submit, which you'd imagine would not work as a field is highlighted as invalid - actually, it does work and the page submits.
Can anyone help to explain why this is happening and how to stop it? Thanks very much.