admin管理员组

文章数量:1291197

Is there any existing jQuery functionality that can test if characters entered into a textbox are either numeric, or valid in a number?

Such as

.00 or 0.00, but not 0.00.00 or 0a

What I'd like to do is catch any invalid characters before they appear in the textbox.

If it's not possible with jQuery, what's the best way to approach this?

I know with JavaScript I can test isNaN() and then return false, but that's going to start getting hairy when I have to account for all possible keystrokes.

Is there any existing jQuery functionality that can test if characters entered into a textbox are either numeric, or valid in a number?

Such as

.00 or 0.00, but not 0.00.00 or 0a

What I'd like to do is catch any invalid characters before they appear in the textbox.

If it's not possible with jQuery, what's the best way to approach this?

I know with JavaScript I can test isNaN() and then return false, but that's going to start getting hairy when I have to account for all possible keystrokes.

Share Improve this question asked Oct 19, 2010 at 20:57 DaveDevDaveDev 42.2k73 gold badges232 silver badges394 bronze badges 1
  • 1 What about 1,000.00? Would yo consider that valid? – Peter Ajtai Commented Oct 19, 2010 at 21:16
Add a ment  | 

5 Answers 5

Reset to default 9

just use a regex match

$('#formelement').val().match(/[-+]?[0-9]*\.?[0-9]+/)

(excluding selector, everything else is plain javascript)

As noted in ments, since you need to do it for each character inserted you have to consider an empty decimal part valid (eg. /[-+]?[0-9]*\.?[0-9]*/)

Since people in ments forces me to be precise I can suggest you how to work out how to use this matching for your purpose (but so you don't let anything to the OP imagination :( )

You can split the regex in 3 regexs, one for the first part (eventual sign and whole part), one for the first part plus the dot symbol and one for the whole number.

You validation routine should accept the input while it's being written if it matches at least one of the threes regex just described and the validation done at the end should accept just when the last regex is matched (since you are submitting the value and you need it to be correct)

It's a little tricky, since you want to make sure you can enter all numbers left to right, but something like this:

$("input").keyup(function() {       
    this.value = this.value.match(/[-+]?[0-9]*\.?[0-9]*/);
});

Try it out with this jsFiddle

Note how I'm checking the number from left to right. This means that + must be valid. Also 5. must be valid, or you could never enter 5.0 or +5.

Now the above has some major issue (try the arrow keys).

Here's a slightly more elegant solution that acmodates a default value as well:

$(function() {                      // <== DOC ready

    var prev="";                    // Initial value to replace default text with

    $("input").click(function () {  // Include a select on click
        $(this).select();           // if you have a default value
    });

    $("input").keyup(function() {  

        if(/^[-+]?[0-9]*\.?[0-9]*$/.test(this.value)) // If number....
            prev = this.value;                        // store it as the fallback
        else
            this.value = prev;                        // else go to fallback
    });
});

Try it out with this jsFiddle

Example HTML for the above:

<input type="text" value="Enter only a number" />

Note how when you use .test() you have to test from the beginning ^ to the end $.

Seems like a work for regular expressions:

var x = '0.00';
var y = '0.000.00';
x.match(/^[0-9]+\.*[0-9]*$/); 
y.match(/^[0-9]+\.*[0-9]*$/); // evaluates to null

You can use a plugin or another separate library to do form validation. An example: http://www.geektantra./2009/09/jquery-live-form-validation/

Regular expressions would also work if you wanted to handle this manually.

I'm using this plugin for my projects: http://www.texotela.co.uk/code/jquery/numeric/

it's simple but have some bugs with negative values, anyway it works great for a simple use!

you can you use it like so:

$("input.numericInput").numeric();

本文标签: javascriptHow to ensure only valid numeric characters are entered into a textboxStack Overflow