Hi, Is there a library out there which I can use in my current ASP.NET app, to validate queryStrings?
Edit ~ Using Regex to look for patterns, like string, only, numeric only, string with length x,...etc
Thanks
Hi, Is there a library out there which I can use in my current ASP.NET app, to validate queryStrings?
Edit ~ Using Regex to look for patterns, like string, only, numeric only, string with length x,...etc
Thanks
Don't know about a library, but you can use to check if the querystring exists:
if (!String.IsNullOrEmpty(Request.Querystring["foo"]))
{
// check further
}
else
{
// not there, do something else
}
If you want to use Reglar Expressions to further validate, you can create a class that accepts the string and return a boolean.
public static Boolean IsValid(String s)
{
const String sRegEx = @"regex here";
Regex oRegEx = new Regex(sRegEx , RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
MatchCollection oMatches = oRegEx.Matches(s);
return (oMatches.Count > 0) ? true : false;
}
This is a good free program to help you build the regluar expressions: Expresso
Do you mean to ask about breaking the query string into its parts? ASP.Net already does that for you. You can access the individual paramaters via the Request.QueryString collection.
For the query string: ?fruit=apple&socks=white
Request.QueryString["fruit"] will give you "apple", and Request.QueryString["socks"] will give you "white".
If you're talking about validating the query string for requests as they come in, the .NET Framework already does this. Page has a property called ValidateRequest that's true by default, and anything invalid in the query string will cause an error (the first time the query string is accessed in your code behind) without your having to do anything.
If you're talking about validating query strings you have as data or something, then this MSDN Mag article may help you.
EDIT: I see you're asking more about data validation. You should find some good stuff in the MSDN article I linked above.
The best approach for this sort of thing would probably be to use regular expressions to check whatever condition you are looking for.
It would be good in an actual scenario to separate the validation from the presentation but just for the sake of an example:
if (!string.IsNullOrEmpty(Request.QueryString["Variable"]))
{
string s = Request.QueryString["Variable"];
Regex regularExpression = new Regex("Put your regex here");
if (regularExpression.IsMatch(s))
{
// Do what you want.
}
}