Mega Code Archive

 
Categories / Delphi / Examples
 

Validchars

VALIDATING INPUT USING 'CHARACTER SET' VARIABLES... Richard Nov '98 **************************************************************************** 'FileName' example. bearing in mind that the following characters are not allowed in filenames \ / : * ? " < > | (along with lots of unprintably BAD characters -if you didn't laugh you're an anorak) then we can assume that the valid filename set includes characters from the '!' (ascii 33) to the '~' (ascii 126) MINUS the above baddies. So using sets we can set things up like this: type TpossFNameChars = set of Char; var validFNameChars: TpossFNameChars; badFNameChars: TpossFNameChars; begin badFNameChars := ['\','/',':','*','?','"','<','>','|']; validFNameChars := ['!'..'~']; validFNameChars := validFNameChars - badFNameChars; and then we might say something like this: if not(charArray[index] in validFNameChars) then begin {whatever} end; **************************************************************************** Example of a whole procedure using a similar technique function ValidInput(InputText : TCaption) : Boolean; {the built-in Delphi IsAlpha() function does not trap things like} {quotation marks... -this is home-made and better} type TvalidInputChars = set of Char; var i,len : Integer; validInputChars: TvalidInputChars; begin {define the SET of valid input characters} validInputChars := ['A'..'Z', 'a'..'z']; i := 1; {Note: Delphi puts text from an input box into the box's .Text property when} {focus shifts away from that box, and the TYPE of this text property is} {TCaption} len := Length(InputText); {the first byte of yer actual string here contains length information...} {so go from index 1 upwards...} for i := 1 to len do begin if InputText[i] in validInputChars then begin Result := True end else begin Result := False; Break; end; end; end; **************************************************************************** and another example: function TForm1.ValidateInput(inputString: String): Boolean; {ensure that each character of the user's input is a character with the following characteristics: it must be a character form the 'normal' ASCII range of 0 to 127, it must be a VISIBLE character, and it must also be in the ranges 'A' to 'Z' and 'a' to 'z'!!!...} type TplainASCIIChars = set of Char; var plainASCIIChars: TplainASCIIChars; inputLen: Integer; badChars: Boolean; begin plainASCIIChars := [Chr(65)..Chr(90), Chr(97)..Chr(122)]; badChars := False; inputLen := Length(inputString); {copy the search pattern into an array before validating it...} for i := 1 to inputLen do begin tempArray[i - 1] := searchPatt[i]; end; tempArray[i - 1] := #0; {and look for dodgy characters in the search string...} for i := 0 to (inputLen - 1) do begin if not(tempArray[i] in plainASCIIChars) then badChars := True; end; if (badChars = True) then Result := False else Result := True; end.