Ganymede
Ganymede

Reputation: 165

Number validation using jquery

$('#empcontact').blur(function(){
        var stri = $('#empcontact').val();//the input element
        var numbers = "0123456789";
        var flag = false;
        for(var x=0;x<stri.length;x++){
            var ch = stri.charAt(x);
            var n = numbers.indexOf(ch);
            if(n === -1){//why does it always resolve to true            
                flag = true;
                break;
            }
            else{

            }
        }
        if(flag){
            alert("Not a number");
            $('#empcontact').val(" ");
            $('#empcontact').focus();
        }
});

I don't know why it always resolves to true even when numbers are passed also when characters are passed.

Upvotes: 1

Views: 7399

Answers (6)

Fezal halai
Fezal halai

Reputation: 784

Number Validation

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode != 99 && charCode != 118 && charCode > 31
        && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

Upvotes: 0

user3856043
user3856043

Reputation:

Try using Number Validation Plugin that is a plugin for jQuery that performs validation of an HTML input number type.

https://github.com/prednaxela/jquery.numbervalidation

Upvotes: 0

Ishan Jain
Ishan Jain

Reputation: 8161

You can check for number via this:

 function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
 }

OR

function isNumber(n){
  return (parseFloat(n) == n);
}

Because IsNumeric will fail in the following cases:

IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;

IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;

Or If you want to use Regexp for this, there are many Regexp available for this:

/^[0-9]+$/

/^\d*$/

[0-9]+(\.[0-9][0-9]?)?

Upvotes: 1

th1rdey3
th1rdey3

Reputation: 4358

A javascript solution would be

if(isNaN(parseInt('a'))){ // replace 'a' with your variable
    flag = true;
    break;
}

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could use $.isNumeric(),like:

var stri = $('#empcontact').val();
console.log( $.isNumeric( stri ) ); //returns true if is number

or

var stri = $('#empcontact').val();
console.log(typeof stri === 'number' && isFinite(stri) ); //returns true if number

or only integers

var intsOnly = /^\d+$/,
    stri = $('#empcontact').val();
if(intsOnly.test(stri)) {
   alert('its valid');   
}

Upvotes: 7

Robin
Robin

Reputation: 7895

Looks like a good regex situation to me, use:

if(stri.match(/^[0-9]*$/)){
    alert("numeric!");
    // do whatever else...
}

$.isNumeric will allow crazy semi-numeric stuff like 0xFF and 2e5.

Upvotes: 0

Related Questions