0

/^[0-9]\s[0-9]/[0-9]$|^[0-9]/[0-9]$|^[0-9]$|^[0-9],[0-9]$|^[0-9].[0-9]$/.test("1 1") is giving true. Why? I want only following type of strings to return true to above check: "1 1/2", "1/2", "1,2", "1.2", "1"

Also, I need to allow ½ character. Its not 3 characters but 1. It is available in Swedish keyboard.

Also, I am checking this in onchange event of an asp.net textbox. If it returns false, I don't want page to postback and call the event handler of textbox's textchanged event. For this, I used event.preventDefault() but it does not work. Below is the markup of the textbox.

<asp:TextBox ID="gvtxtQty" CssClass="qty_input" runat="server" BackColor="#f4f6f7" Width="100px"
                                                                                    Text='<%# Eval("Qty")%>' OnTextChanged="gvtxtQty_TextChanged"></asp:TextBox>

And I register the change event for the textbox like below.

$(".qty_input").change(function (e) { fnVerifyQuantity(e, this) });

Function fnVerifyQuantity is as below:

function fnVerifyQuantity(e,o) {
        var bol = /^[0-9]\s[0-9]\/[0-9]$|^[0-9]\/[0-9]$|^[0-9]$|^[0-9],[0-9]$|^[0-9].[0-9]$/;
        //var bol = /[0-9]\s[0-9]\/[0-9]/;
        var tf = bol.test(o.value);
if(tf=="false") e.preventDefault();

Please help.

user2861226
  • 169
  • 13

1 Answers1

0

1/ Your first regepx returns true because you forgot to escape the point in the last part: ^[0-9].[0-9]$ should be ^[0-9].[0-9]$

2/ For the ½ character, it's unicode to you can not reliably using regexp to match it, I suggest that you first "normalize" your value and then use a more simple regexp.

3/ Your have a mistake in your last test, the "tf" variable is a boolean so you should not compare it to a string, your test should be "if(!tf)" or "if( false == tf )"

Here is a modified version of you last code that should work:

function fnVerifyQuantity(e,o) {
    var str = o.value.trim().replace("½", ".5").replace("1/2", ".5").replace(" ", ".").replace(/[,.]+/, ".").replace(/^\./, "0.");
    console.log("Aligned string: " + str);
    if( !/^[0-9](\.[0-9])?$/.test(str) ) {
        console.log("not conform");
        e.preventDefault();
    }
    else {
        console.log("conform");
    }
}
Romain
  • 573
  • 3
  • 8