I want my field to accept only integers and i have

2019-03-06 16:24发布

问题:

This question is an exact duplicate of:

  • Required field that should be filled only with integers 1 answer

I have got my complete project done but it is lacking this one requirement and i'm not able to solve this issue in my project myself.

回答1:

Could you use CodeIgniter's form validation? And set a rule like this:

$this->form_validation->set_rules('yourfield', 'Your field\'s human name', 'required|integer');

This assumes that the field is called yourfield.


After reading the comments, it seems like you want to check if value in the field is an integer using jQuery. I'd suggest looking into this plugin: jQuery - numeric

There's a good example of to use it here.

Here's the relevant code:

If you had an input like this:

<input class="integer" type="text" />

Then you can validate it, checking that it is an integer, like this:

$(".integer").numeric(false, function() { alert("Integers only"); this.value = ""; this.focus(); });

However, as JavaScript/jQuery is run on the client-side (and can be bypassed), I would stress that it is very important to also validate on the server-side, in this case using PHP. This excellent answer explains in more detail why both are important.



回答2:

USE HTML5

<input type="number" min="0" />


<input name="Est_Value" id="estvalue" class="regi_input_1" style="width: 150px; height: 25px;" type="number" min="0" />

Validation Using JavaScript

<input name="Est_Value" id="estvalue" class="regi_input_1" style="width: 150px; height: 25px;" type="text" onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )){ alert('numbers only'); return false; }" />

Working Demo http://jsfiddle.net/cse_tushar/FEVrB/