views:

324

answers:

3

Hi,

My application uses unicode characters and i have several text fields where i want to restrict user from inputing special characters like :'";

begin
    if not (Key in ['a'..'z','A'..'Z',' ','0'..'9',#13,#8]) then
        Key := #0;
    if Key = #13 then
        bOk.Click;
end;

So at this point it lets user add spaces and use a backspace key to erase, and of course Enter key to comfirm.

There are few unicode characters i want to let being inputed also. ą, č, ė, į, š, ų, ū, ž and their uppercase alternatives, but just adding them to the set like so...

Key in ['a'..'z','A'..'Z',' ','0'..'9',#13,#8,'ą'..'ž','Ą'..'Ž']

... does nothing and i still can not write these symbols in the text field.

I would like to know, how to fix this problem. Is there a way to tell if the pressed key is the unicode character i'm looking for?

Thank you

+7  A: 

If you're on D2009 or later there's a unit named Character containing functions like IsLetterOrDigit, IsLetter, etc. all handling specifically what you need.

utku_karatas
Thank you, i have read help file on 'Character' and it solved my problem. I have changed my 'if' statement like so: 'if not IsLetterOrDigit(Key) and not CharInSet(Key,[#8,#13,' ']) then'.
+4  A: 

Please pay attention to Hints and Warnings when you compile your apps. To ignore them is to ignore potential problems.

You should be getting warning that "WideChar is reduced to byte char...". Therein lies the problem: the Key is no longer Unicode in your set operation!

The warning advises you to use CharInSet; you can also look at TCharacter (a special class with class functions to identify certain categories of characters). If neither of these suit your requirements, then use a string constant with all the valid characters, and use the Pos function to determine if the Key is present.

Finally, you may rather want to consider excluding specific characters as opposed to trying to think of every specific character you want to include.

Craig Young
Very helpful answer too. Thank you. String with specific characters and Pos function is very handy in cases where i want to let or restrict to write certain characters.