The AppGini Blog
A few tips and tricks to make your coding life a tiny bit better.

How to allow numbers only in a field

Let’s say you have a numeric field, maybe a price, a score or some other field that should contain numbers only. If you set the data type of the field in AppGini (or in your database) to be numeric (INT, DECIMAL, FLOAT … etc) that would allow only numbers to be stored in the database.

But you might still wish to alert the user that only numbers are allowed before she saves the record. Here is how to do it in JavaScript:

First, you should place this code in the hooks/footer-extras.php file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<script>
$j(function() {
  AppGini.numericOnly = function(fieldname) {
    setInterval(function() {
      var field = $j('#' + fieldname), val = field.val();
      if(val == parseFloat(val)) return;
      val = parseFloat(val.replace(/[^\d.-]/g,''));
      if(isNaN(val)) { field.val(''); return; }
      field.val(val);
    }, 1000);
  };
})
</script>

Next, also in the hooks folder , create a file named tablename -dv.js (where tablename is the name of the concerned table) if it’s not already there, and add this code to it:

1
2
3
4
$j(function() {
  AppGini.numericOnly('field1');
  AppGini.numericOnly('field2');
})

Change field1 and field2 in the above code to the actual names of the fields that you want to set to accept only numeric values. Add more lines if you have more fields or remove a line if you have only one numeric field.

The above code would remove any non-numeric characters that the user types, on the fly. And it would still allow negative sign and decimal point.