vcl - Delphi- Make a EditBox to accept only numbers lessthan or equal to(<=) 12 on Keypress event -
this question has answer here:
- only specific numbers in edit box 2 answers
i have edit box , trying make accept numbers 0 12. wrote onexit handler this:
procedure tfrmcourse.edtdurationexit(sender: tobject); begin if not string.isnullorempty(edtduration.text) begin if strtoint(edtduration.text) > 12 begin edtduration.clear; edtduration.setfocus; end; end; end;
... want check while typing. tedit should accept numeric input , warn when value > 12.
answer propose question
final answer
procedure tfrmcourse.edtdurationkeypress(sender: tobject; var key: char); var stextvalue: string; begin if sender = edtduration begin if (key = formatsettings.decimalseparator) , (pos(formatsettings.decimalseparator, edtduration.text) <> 0) key := #0; if (charinset(key, ['0' .. '9'])) begin stextvalue := tedit(sender).text + key; if stextvalue <> '' begin if ((strtofloat(stextvalue) > 12) , (key <> #8)) key := #0; end; end end; end;
the conversion function strtoint()
raises econverterror
if entered characters not numeric. can deal setting tedit.numbersonly
property. suggest use trystrtoint()
function instead (or in addition). although said want check while typing suggest using onchange
event, because catches erroneous input pasting clipboard.
procedure tform5.edit1change(sender: tobject); var ed: tedit; v: integer; begin ed := sender tedit; v := 0; if (ed.text <> '') , (not trystrtoint(ed.text, v) or (v < 0) or (v > 12)) begin ed.color := $c080ff; errlabel.caption := 'only numbers 0 - 12 allowed'; exit; end else begin ed.color := clwindow; errlabel.caption := ''; end; end;
the errlabel
label near edit box gives user indication of erroneous entry.
Comments
Post a Comment