Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check input fields for numbers and hyphen

Tags:

jquery

I just want to check if a input-value is numeric and/or has a hyphen between two numbers. Comma should be replaced by point (1,23 -> 1.23) and spaces should be deleted.

Allowed values are i.e.:

1
2
1-2
34-45

Not allowed:

-2
1-
-
any letters

My attempt:

$('form').submit(function( event ) {
    $('input').each(function(index, element) {
    $(element).val($(element).val().replace(",", ".").replace(" ", "")); // replace comma, delete spaces
    if (!$.isNumeric($(element).val())) {
        alert("error");
        event.preventDefault();
    }
    // else submit
});

I think isNumeric is the wrong way, as '12-5' should be a valid value...

like image 245
user3142695 Avatar asked Dec 30 '25 16:12

user3142695


1 Answers

First thing to do is to replace the , with . and remove spaces. This can be done by:

var input = "1 2 3. 4 - 56,78"; input.replace(/ /g,"").replace(/,/g,".")

Then you have to apply regex:

/^\d+(\.\d+|\d*)(-?\d+(\.\d+|\d*)|\d*)$/

fiddle: http://jsfiddle.net/y5ACh/1/

regex explanation: http://www.regexr.com/397j6

forgot to mention - I assumed that strings like .2-31 are invalid ($.isNumeric(".2") returns true, so we can't use $.isNumeric on each, before and after -)


For floats to be invalid you need to drop the (\.\d+|\d*) groups: http://jsfiddle.net/y5ACh/2/

For integers to be invalid you need to drop the \d* groups: http://jsfiddle.net/y5ACh/3/

like image 88
eithed Avatar answered Jan 02 '26 09:01

eithed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!