Jui Test
Jui Test

Reputation: 2409

Validation for integer number

I have created one form.In that form,it put one textbox.That text box should take only integer not character or float.So I applied validation like this.Does it right?

var a = document.getElementById('textbox1').value;
var b = /^\d+$/;

If (a.search(b) == -1)
{
alert(Must be Interger);
return false;
}

Upvotes: 0

Views: 2126

Answers (4)

ajimix
ajimix

Reputation: 992

This should work:

var textboxValue = document.getElementById('textbox1').value;

if (!textboxValue.test(/^\d+$/)){
    alert('Must be Interger');
    return false;
}

Its a good practice to put easy names to vars or you will be lost months later whan you review your code :D

Upvotes: 0

Java
Java

Reputation: 2489

You can use this script for Integer validation .

   var value = Number(intfield.value);
if (Math.floor(value) == value) {
  // value is integer, do something based on that
} else {
  // value is not an Integer, show validation alerts
}

Upvotes: 2

Bhanu Prakash Inturi
Bhanu Prakash Inturi

Reputation: 19

Hi I think below answer will be the better so that you can implement multiple TextBoxes

 <script> 
     function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 45 || charCode > 57)) {
            return false;
            return true;
        }
    }
 </script>

Thanks Bhanu Prakash

Upvotes: -1

Andy Ray
Andy Ray

Reputation: 32076

Yes, that will work, unless it's allowed to take a negative integer, in which case you need to add -? (optional negative sign) before the \d

Upvotes: 2

Related Questions