haitruonginfotech haitruonginfotech - 2 years ago 122
Javascript Question

Error javascipt key in invalid format integer

<input type="text" name="quantity">

I want this is a number(allow 0-9 and -), this is my code:

function update_quantity() {
$(this).val($(this).val().replace(/[^-?\d]/g, ''));
$(document).on("change, keyup", "input[type=text])", update_quantity);


123 -> valid
-123 -> valid
123- -> invalid
-1-12-123 -> invalid
-123-12 -> invalid

-> error can't auto replace -123-12 to -12312 or 123- to 123, how to fix it

Answer Source

This seems to be what you are looking for:


$(document).ready(function() {
  $('input[name=quantity]').on('keyup',function() {
    var v = $(this).val();
    if (!v.match(/^-?[0-9]*$/))

Though I would personally do it on change or blur instead of stripping as user enters. Or better yet, return a visible error and prevent form submit, rather than auto-replace. I really hate form fields that do this sort of thing. Makes for bad UX IMO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download