开发者

JavaScript and regular expression, only numbers and . ,

开发者 https://www.devze.com 2023-01-26 02:01 出处:网络
Regular expressions is not my thing. Hope you can help me here. I have this right now: /^[0-9]+$/ and i need to change it, so it will allow numbers from 0-9 and only \",\" to be in the string 1 ti

Regular expressions is not my thing. Hope you can help me here.

I have this right now:

/^[0-9]+$/

and i need to change it, so it will allow numbers from 0-9 and only "," to be in the string 1 time. After the , we can only have as many digits we want but only 2 digits before the ",".

allowed: 66,6666 - 6,66 - 6,6 Not allowed: 666,66 - 66,666abc - abc,666

Hope you can help.

Code:

$("#discountCodeAmount").keyup开发者_StackOverflow社区(function() {

        var nAmount = $("#discountCodeAmount").val();
        var kronerExp = /^[0-9]+$/;
        var procentExp = /^[0-9]{1,2},[0-9]+$/;

        if($('#typeProcent').is(":selected") && !nAmount.match(procentExp)) {
            errorDialog("error");
            $("#discountCodeAmount").val("");
            $("body").focus();
        }
        else if(!nAmount.match(kronerExp)) {
            errorDialog("error");
            $("#discountCodeAmount").val("");
            $("body").focus();
        }
});


/^[0-9]{1,2},[0-9]+$/


/^[0-9]{1,2},[0-9]+$/


This should do the trick:

/^\d{2},\d+$/


Working example

    $("#discountCodeAmount").blur(function() {  
        checkType();      
    });        

    function checkType() {
        var nAmount = $("#discountCodeAmount").val();
        var kronerExp = /^[0-9]+$/;
        var procentExp = /^[0-9]{1,2}(?:,[0-9]+)?$/;

        if($('#typeProcent').is(":selected") && !nAmount.match(procentExp)) {
            errorDialog("Der opstod en fejl!","Angiv en procentdel mellem 1 og 99.");
            $("#discountCodeAmount").val("");
            $("body").focus();
        }
        else if($('#typeKroner').is(":selected") && !nAmount.match(kronerExp)) {
            errorDialog("Der opstod en fejl!","Angiv kun tal i feltet.");
            $("#discountCodeAmount").val("");
            $("body").focus();
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消