Is there any object in the .NET framework that will sanitize a string so that it is safe to use as the "id" attribute value for an HTML tag?
A:
Not that I am aware of. You could look at the specification for allowed characters and implement it. Note that this might me more difficult because you need to make sure that the identifier is unique within the HTML document.
Darin Dimitrov
2010-01-04 17:01:27
+1
A:
System.Web.HttpUtility.HtmlEncode() is the closest thing I can think of.
consultutah
2010-01-04 17:07:15
What if the string starts with a digit?
Darin Dimitrov
2010-01-04 17:13:20
I hadn't looked at the spec until just now, but it is a lot more restrictive than what most browsers actually allow for an id attribute: 'ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").' Making sure it follows that wouldn't be too hard, but you would want to verify that it is unique.
consultutah
2010-01-04 17:50:38