0

I have this script which only allows 0-9 and - characters for negative numbers. However this does not prevent a user from entering 123- for example and it causes errors. Is there a workaround for this? I prefer to stick to JavaScript as much as possible. But I am open to plugins if there is no other way.

It is working well by not allowing other characters such as letter. But I need to prevent users from entering - at the end or any other part aside from the start of the line.

function validate(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[0-9-]|\./;

    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    }
}
jasonscript
  • 6,039
  • 3
  • 28
  • 43
aozora
  • 423
  • 3
  • 13

4 Answers4

1

jsFiddle

JS

// validates the key down event
function validate(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    // checks if it is a digit or first char is a -
    if (!/^-?\d+/.test(key)) {
        console.log(key);
        // stops event 100% if it isn't what you want
        evt.stopPropagation();
        evt.preventDefault();  
        evt.returnValue = false;
        evt.cancelBubble = true;
        return false;
    }
}

Regex

^-?\d+$

Regular expression visualization

Description

/-?\d+/
^ assert position at start of the string
-? matches the character - literally
    Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
\d+ match a digit [0-9]
    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string
abc123
  • 17,855
  • 7
  • 52
  • 82
0

if you like regexp you can try using this

(-|[0-9]?)[0-9]+

It means start is either - or a number. Then followed by only number

Evilsanta
  • 1,032
  • 11
  • 18
0

You just need to modify your regex a little!

var regex = /-?\d+/

the ? means 0 or 1 and d+ will verify digits only.

Sezu
  • 1
  • 2
0

Matching only positive and negative integers can be done with the regex /^-?\d+$/.

Explanation:

^ - start of string

-? - optional negative sign {greedy; 0-1}

\d+ - one or more decimal digits, i.e. [0-9] {greedy; 1-infinity}

$ - end of string

Demo:

> /^-?\d+$/.test('42')
true
> /^-?\d+$/.test('-42')
true
> /^-?\d+$/.test('42-')
false
> /^-?\d+$/.test('a42')
false
> /^-?\d+$/.test('42b')
false
Shashank
  • 13,713
  • 5
  • 37
  • 63