Saturday, March 31, 2012

String validation in C#?

I'm a 30 year codingveteran using mostly S370 Assembler and Pascal on the PC's. I'm gettingmy feet wet in C#, and having a dickens of a time figuring out trivialthings. The crisis de jour is determining if a string is "valid" beforeletting XML barf all over it for containing a Hex 06 or some such.
In Pascal, I'd define a constant, ValidChars:
ValidChars = ['0'..'9', 'A'..'Z', 'a'..'z', #5, #10, #13];

andsimply iterate over the string (The lightbulb is [ i ] - How do you escape emoticon stringsin this editor?):
for i := 1 to length(arg) do
if argIdea [I] not in ValidChars
then begin
<bad string stuff>
break;
end;

I can't find anything about sets in the C# doc, so maybe theINpredicate isn't going to fly. So, maybe a CASE statement on theordinals of the various characters. Nope, no case statement. There's aswitch, but it appears not to like case definitions of> " ". Maybe it's there but I can't figure out (other than 255 cases!) how to use it.
Note, I'm looking for "the C# way", for anelegantsolution. I went to find the ord (ordinal) function, and see I didn'teven have a list of string functions, char functions, or functions ingeneral (that I could find). It must be in there somewhere.Obviously, the "language" is just the bnf of the symbols and justa few rules about operators, etc.. But the "reality" is that functions,methods, properties, etc. are built into what MS distributes, and theremust be doc on these things somewhere. I can WRITE an ordfunction, but I'm certain I'd be duplicating some efforts built intothe distribution.
TheInElegant solution I have running is pretty ugly.

private string CheckData(string arg, bool debug)
{ int loop1;
bool valid = true;
for (loop1=0; loop1 < arg.Length; loop1++)
if ((arg[loop1] != "\t"[0])
&(arg[loop1] != "\r"[0])
&(arg[loop1] != "\n"[0])
&(arg[loop1] < " "[0]))
{ valid = false;
break;
}
if (valid)
return arg;
else if (debug)
return "|Invalid String|";
else
return "";
}

Maybethis is the best C# can do, but I sincerely doubt it. It's 35 yearsPascal's junior, it should have some elegance built-in!
Possiblythere is a web reference or even a book someone might suggest to getover the odd organization of the language doc in .Net.
tiaUse regular expressions...

EDIT
You use Regular Expression to do validations. To your other questions Predicates are in standard Arrays and all the Math functions are under System.Math but I think the class is Sealed. Try the links below for the FCL(framework class library) 2.0 and a free book that covered all the math functions in C#. A good book try Programming .NET by Jeff Prosise. I did not cover the string functions, they are under strings and formatting, run a search on MSDN because it takes a book chapter to cover. Hope this helps.
http://beta.asp.net/QuickStartv20/util/classbrowser.aspx

http://www.brpreiss.com/books/opus6/html/page10.html

0 comments:

Post a Comment