Hi hon,
Validations is a very broad subject. The most basic you can do I guess is to look for illegal characters.
Code:
type
TCharSet = set of char;
function containsIllegal(aString:string;illegal:TCharSet):boolean;
var
loop : integer;
begin
result:=false;
for loop:=1 to length(aString) do
if (aString[loop] in illegal) then
begin
result:=true;
exit;
end;
end;
That function will return true when it finds the first instance of a character that is in the set 'illegal'. To use it, do things like this...
Code:
if (containsIllegal(aPhoneNumber,[#0..#$1f,#$7f..#$ff,#$21..#$2A,#$2C..#$2F,#$3a..#$7e]) then
begin
// take action
end;
That will return true if the string you pass to it contains any character other than <SPACE>, + and 0 to 9. Thats basic validation.
For things like number, you can do it two ways...
Code:
try
aNumber:=strToInt(aString);
except
// Exception occured, the number in aString is invalid... take action
end;
Or you can have it default to some value, like this...
Code:
aNumber:=strToIntDef(aString,aDefaultValue);
As for dates, you should look at (IIRC) shortDateFormat.... make a copy of that variable, and then change it to the format of the date you are trying to validate... eg. dd/mm/yy. Try converting the string containing the date with StrToDate. If you get an exception, the date is invalid. StrToDate may have the option to allow you to specify the format you wish to use... (older versions didn't).
One option you do have, is regular expressions... get a hold of a free regex implementation if you don't have regex functions available to you and learn how to use them. They can be incredibly powerful.
Failing this (is it Turbo Pascal you're using?), then you will need to be prepared to write a set of routines that do the validation for you, by inspecting string lengths, the positions of characters, the characters in the string etc. It can be a pain in the rear. So, basically, create a function called 'validDate' for example, that will parse the string passed to and check whether the data is in the right place, and have it convert the date and check that it makes sense... to be thorough, you should include a check for 29th Feb (there are formulae available). As you go, build up a library of these sorts of functions so you can reuse them further down the line.
Hope this helps.
Bookmarks