1

this is what I have so far:

$j(element)..keypress(function(e){
        var val = $j(this).val();
        if (("1234567890.").indexOf(e.charCode) > -1){
            if (val.length > 0){
                var regex = /(\+|-)?(\d*\.\d*)/;
                if (regex.test(val)){
                    return true;
                } else {
                    return false;
                }       
            } else {
                return true;
            }
        } else {
            return false;
        }
    });

but for some reason, the text field only allows one character... and not even a number

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352

3 Answers3

2

This checks a decimal number, with an optional +/- sign character. Found under 5sec in google. /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • what's wrong with doing it this way? (\+|-)?(\d*\.\d*) this makes it so the decimal is optional, but the decimal itsself can still be present. – NullVoxPopuli Feb 09 '12 at 03:06
  • I didn't check the actual code but it seems correct, I just copy/pasted from http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html – elclanrs Feb 09 '12 at 03:09
  • apparently, the problem is that I'm not doing the test after the text has been entered or something – NullVoxPopuli Feb 09 '12 at 03:10
  • Why do you need to do it in the `keypress` event? I've been trying solutions but it gets complicated. Basically, the first character and the `.` get rejected. I tried with `keyup` and it seems to solve the first character thing but not the `.`. It might be easier to just validate with a button...Look http://jsfiddle.net/9U2Mw/2/ – elclanrs Feb 09 '12 at 03:46
  • but it needs to be as they type.. otherwise whats the point of a forced validation field? =p – NullVoxPopuli Feb 09 '12 at 03:55
  • 1
    What about just detecting numbers and `.` on `keypress` with something like `if ( (e.which >= 48 && e.which <= 57) || e.which == 190 || e.which == 110 ) { // blabla }`. And then validate on submit? There's still a small chance they might input something invalid like `12.4.55` tho. – elclanrs Feb 09 '12 at 04:04
2

First, shouldn't the return be the opposite? true if the test succeeds, false otherwise?

Second, . in a regex means "any character". If you want to match just a dot, use \.

This way your regex will work. However, for a better result, use the regex provided by elclanrs.

Note: it seems the value still hasn't changed when the keypress runs, so it's the old value that is being matched, not the new one.

Update: this is not an ideal solution, but will work nonetheless - You can use the code in this question to watch for changes in the input's value (it uses polling, though):

$(element).watch("value", function(propName, oldVal, newVal) {
    var regex = /^(\d*\.?\d*)$/;
    if (!regex.test(newVal)){
        $(this).val(oldVal);
    }
});
Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • yeah, I noticed that after, I posted. but on Rubular.com, this (\+|-)?(\d*\.\d*) works with this test string: 23.43 23. .32 0.23 43.54 23 -23 -45.34 -.43 -0.34 but now I can't type anything in the text field – NullVoxPopuli Feb 09 '12 at 03:05
  • Yeah, I just noticed that (see my update). We need to find a way to do the check for the updated string... – mgibsonbr Feb 09 '12 at 03:08
  • hmm. I must check the jquery api then – NullVoxPopuli Feb 09 '12 at 03:11
  • if you find a better solution, post here, I'm interested in it too. However, see my update for a short-term workaround. – mgibsonbr Feb 09 '12 at 03:26
  • i'll update with my current function. it behaves the same as in my original question, but I feel better about it. – NullVoxPopuli Feb 09 '12 at 03:36
  • If you don't want to try my solution, here are some ways of improving yours: You're forgetting the `^` and `$` in the beginning/end of your regex (it must match **all** the input, not any part of it). Also, make the `\.?` optional, or everything will break unless the first char you type is `'.'`. At last, include `+` and `-` as valid characters in your `indexOf` test (it'd also be good to include `\b` and to allow arrow keys, or the field will be hard to navigate/edit). Hope it helps! – mgibsonbr Feb 09 '12 at 04:00
  • awesome, thanks. this is the fiddle I've come up with: http://jsfiddle.net/9U2Mw/4/ now it just needs to not allow 2 '.' – NullVoxPopuli Feb 09 '12 at 04:05
  • Try [this one](http://jsfiddle.net/mgibsonbr/NJNkc/), made it using the contributions I got after asking [this question](http://stackoverflow.com/q/9205164/520779). If you don't like the `goodPrefix` thing, just adapt it to always reject invalid inputs (but according to [this answer](http://stackoverflow.com/a/9205475/520779), it's not necessarily a good idea...). – mgibsonbr Feb 09 '12 at 05:37
  • this is what I think might be the best solution: http://stackoverflow.com/a/9205380/356849 – NullVoxPopuli Feb 09 '12 at 05:59
2

With the help of @elclanrs and @mgibsonbr, I came to this:

$j = jQuery.noConflict();
$j(function() {
    $j("input").keypress(function(e) {
        var val = $j(this).val();
        var regex = /^(\+|-)?(\d*\.?\d*)$/;
        if (regex.test(val + String.fromCharCode(e.charCode))) {
            return true;
        }
        return false;
    });
});

which can be tested here: http://jsfiddle.net/9U2Mw/5/

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352
  • Type `+`, click before it, type `2`. IMHO you're making users' lifes more difficult, without preventing invalid input for all cases. But I already presented my opinion, if you really prefer the `keypress` approach, go with it. – mgibsonbr Feb 09 '12 at 07:03
  • oh, well for that, I'd just need to find a way to not allow typing before a + or - – NullVoxPopuli Feb 09 '12 at 14:51