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:

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:

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.

Published by Genedy

I'm the founder of BigProf Software. We're a tiny team of developers who create tools that make it easy (and affordable) for anyone to create connected business applications that work from any device with a browser.

2 replies on “How to allow numbers only in a field?”

  1. I tried this but I can’t get it to work. I added the exact code into the hooks/footer-extras.php file and created a file expenses-dv.js in the hooks folder, expenses being the table name and cost being the field that I want to control. The cost field is set to decimal with 2 places for precision.
    My expenses-dv.js code is:
    $j(function(){
    AppGini.numericOnly(‘cost’);
    })

  2. Let’s try to debug this issue. While in the detail view of the expenses table, press F12 to open the inspector window, go to the ‘Console’ tab, and type this:
    AppGini.numericOnly('cost');
    After hitting Enter, do you see any errors? If not, doe the cost field now allow numbers only?

Comments are closed.