Ads

Ads

Translate

Friday, 9 November 2012

Validating numeric input

By Fajar  |  November 09, 2012 No comments


Validating numeric input is a common problem -  you want the user to enter a number but how do you make sure he enters a valid one?  User text is normally entered via a TEdit component.   In the object inspector window (F11) there is an events tab and if you click there one of the events will be "OnKeypress".  Double click there and you get the skeleton of a method that is called whenever the user enters a character in the edit box.  We can use this exit to check that the entered character is valid. 

For integers the valid characters are '0' through '9', '-',  and the backspace character.  ('+' could be included but is always redundant since no sign in front of a number means '+')    Delphi defines this set of 12 characters '0' through '9', '-'  and  backspace  as ['0'..'9','-',#8].  (#8 is the decimal number generated when you press the backspace key.)  If the character entered is not one those, we can set the key value to 0 (which tells windows to ignore this key) and beep to let the user know that something is wrong.   The other test we can perform here is to test that there is no more than one  or  '-'  and that if a '-' is  entered it will go at the beginning. 

To be completely safe, there is one other potential error which OnKeyPress can't catch.  We can use an OnChange exit to detect an empty text string and replace it with a '0'.  

Validating floating point numbers (with decimals) is similar except that we must add '.' to the set of valid characters in OnKeyPress.  For generality we can use the global predefined constant DecimalSeparator in place of '.'. (Europeans exchange the dot and comma from proper usage.)  We need to make sure that there at most only a single  DecimalSeparator in the number.    OnChange coding is unchanged from the integer version. 

A program illustrating these techniques is available for download here.  Notice that the same OnChange exit can handle both the integer and floating point number validation.   Similarly, multiple integer edit fields (or multiple floating point edit fields) could share the same OnKeyPressprocedure.  As an added bonus, the program uses a TMediaPlayer component and .wav files to give a little more than the normal beep when an error is made.  

Author: Fajar

Hello, I am Author, decode to know more: In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet.

0 comments:

Best Post This Year

Install Fortesreport community Delphi 7 dan RX Berlin

Download  Pertama2 kita harus punya file installernya terlebih dahulu, download  https://github.com/fortesinformatica/fortesrepo...

Total Pageviews

© 2014 Fajar Priyadi. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates | Powered By Blogger
TOP