简体   繁体   中英

How to restrict only numeric value in input field?

in my code i am restricting only numeric values into my input field for that i am using this code.

if($('.calculator #loan_Amount').val() != "") {
    var value = $('.calculator #loan_Amount').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var intRegex = /^\d+$/;
    if(!intRegex.test(value)) {
        alert('Loan amount must be numeric.');
        return false;
    }
} 

but now if i enter the value 6500.25 it says the value has to be numeric it is not taking the decimal digit as numeric. is any body having idea regarding it

\\d+ means one or more integers not floating number and hence it fails.

Using Regex

Try this \\d+(\\.\\d*)* means

在此处输入图片说明

Using jQuery

Since you already use jquery, so better go with $.isNumeric()

if($('.calculator #loan_Amount').val() != "") {
   if(!$.isNmeric(this.value) {
        alert('Loan amount must be numeric.');
        return false;
    }
} 

With jQuery Masked Input plugin , it is possible to ignore keys other than digits. It can also allow you to do custom digit grouping (aka thousand separator) without having user to hit comma keys. Have a look at the Demo tab on this page .

$('.calculator #loan_Amount').keyup(function(){
    var iptext = $(this).val();
    if(!(iptext.match('^(0|[1-9][0-9]*)$')))
    {
        $(this).val('');
    }
});

this will accept only the neumeric value.

Here is a solution which blocks all non numeric input from being entered into the text-field.

html

<input type="text" id="numbersOnly" />

javascript

var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};​

You can use the JavaScript isNaN(value) method which returns true if value (Not a Number) Otherwise false

  if($('.calculator #loan_Amount').val() != "") {
    var value = $('.calculator #loan_Amount').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    if(isNaN(value)) 
    {
        alert('Loan amount must be numeric.');
        return false;
    }
} 

Hope this Helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM