kthornbloom
kthornbloom

Reputation: 3730

Javascript regex for plain numbers or numbers ending in percent

I am in need of a regex that validates only plain numbers, or numbers ending in a percent. I have tried the following:

/(?!\%$)(\D)/

Which I believe looks for any non-digit excluding an ending percent sign. When I test it, it always returns the same result no matter what though:

http://jsfiddle.net/zow37wLq/1/

Upvotes: 2

Views: 718

Answers (3)

m0meni
m0meni

Reputation: 16445

This regex should work:

/^\d+%?$/

ohaal figured out the problem, but why are you searching for everything that doesn't match instead of searching for what does?

Upvotes: 2

JFrez
JFrez

Reputation: 39

Try this: [0-9]+((px{1}|%{1}))

i usually test my regexp in the following site:

https://www.debuggex.com/

Upvotes: -1

ohaal
ohaal

Reputation: 5268

The error is with your code, not with your regex. See line 9 in your code:

// Set New Image Width
$('#photo-width').on('input', function () {
    var newWidth = $('#photo-width').attr('value'),
        // attempted regex to find any non-digits excluding an ending percent.
        reg = /(?!\%$)(\D)/,
        charTest = reg.test(newWidth);

    // if formatting is incorrect
    if (charTest = true) { // <-------------------------- THIS
        $('.debug').html('<b>Result</b> Please enter only numbers or percents.');
    // if formatting is OK
    } else {
        $('.debug').html('<b>Result</b> Looks OK');
    }
});

The line needs to be needs to be if (charTest == true) {

See updated jsfiddle

Upvotes: 1

Related Questions