NipBoss
NipBoss

Reputation: 173

RegEx test method returns false when it should be true

I've tested the three of the regex's on http://www.regexpal.com/ and they are what I need, but when doing a regex test 2 of them return false (BTC and CAD) and only the Bitcoin address seems to work (you may test with this wallet below).

13dHNxtbckAFM4PzdBqWgymFJmcv3Yzi32

https://jsfiddle.net/ps2fj1ff/1 (all the relevant code is in the html section)

    var regWallet = new RegExp("^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$");
    var regBTC = new RegExp("^\d*\.\d*$");
    var regCAD = new RegExp("^\d+(\.(\d{2}))?$");

    $('#button1').on('click', function() {

        var btcCheck = $('#amount_btc').val();  

        if (regBTC.test(btcCheck)) {

        } else {
            alert("Invalid BTC value!");
        }

        var cadCheck = $('#amount_cad').val();  

        if (regCAD.test(cadCheck)) {

        } else {
            alert("Invalid CAD value!");
        }

        var walletCheck = $('#wallet').val();
        if (regWallet.test(walletCheck)) {

        } else {
            alert("Invalid Bitcoin address, please make sure you've entered a valid address!");
        }
    }); 

Upvotes: 1

Views: 1666

Answers (2)

A. L
A. L

Reputation: 12639

The reason is that in var regBTC = new RegExp("^\d*\.\d*$"); the \ is used to escape the character so if you console.log(regBTC) you will see it as ^d*.d*$.

To prevent this you will have to double escape it: var regBTC = new RegExp("^\\d*\\.\\d*$");

Or better yet use / instead: var regBTC = /^\d*\.\d*$/;

The same goes for the other regex too.

(I initially thought single quote would work too, but apparently not in javascript)

Upvotes: 2

Christopher Reid
Christopher Reid

Reputation: 4484

Use this instead:

var regBTC = /^\d*\.\d*$/;
var regCAD = /^\d+(\.(\d{2}))$/;

It's cleaner and more readable as most editors will give you regexp syntax highlighting in this format.

There really isn't any good reason to use new RegExp which forces you to write the expression as a string, which forces you to use confusing escapes, when there is a proper regular expression syntax built into JavaScript.

Upvotes: 1

Related Questions