Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validating JSONP callback function name in C#
/// <summary>
/// Validation of JSONP callback function names
/// </summary>
/// <remarks>
/// Based off the PHP code at https://gist.github.com/1217080, which is originally based off
/// a blog post at http://tav.espians.com/sanitising-jsonp-callback-identifiers-for-security.html
/// </remarks>
public class JsonValidator
{
/// <summary>
/// Reserved words in JavaScript - These can't be used in callback function names
/// </summary>
private static readonly HashSet<string> _reservedWords = new HashSet<string>
{
"break", "do", "instanceof", "typeof", "case", "else", "new", "var", "catch", "finally",
"return", "void", "continue", "for", "switch", "while", "debugger", "function", "this",
"with", "default", "if", "throw", "delete", "in", "try", "class", "enum", "extends",
"super", "const", "export", "import", "implements", "let", "private", "public", "yield",
"interface", "package", "protected", "static", "null", "true", "false"
};
/// <summary>
/// Regular expression that all callback function names are validated against
/// </summary>
private static readonly Regex _validationRegex = new Regex(@"^[a-zA-Z_$][0-9a-zA-Z_$]*(?:\[(?:"".+""|\'.+\'|\d+)\])*?$", RegexOptions.Compiled);
/// <summary>
/// Validates that the callback function name is valid
/// </summary>
/// <param name="functionName">Name of the function.</param>
/// <returns></returns>
public static bool ValidateCallbackFunction(string functionName)
{
// Ensure each segment matches the regex, and isn't in the reserved words list.
return functionName.Split('.').All(segment => _validationRegex.IsMatch(segment) && !_reservedWords.Contains(segment));
}
}
@braco

This comment has been minimized.

Copy link

commented Aug 14, 2013

This regex doesn't seem to allow "foo.bar"?

This might be better:

/^([a-zA-Z_$][0-9a-zA-Z_$](?:.[0-9a-zA-Z$]+)?(?:[(?:"".+""|'.+'|\d+)])_?){1,}$/

test here:

http://burkeware.com/software/regex_playground.html

@Daniel15

This comment has been minimized.

Copy link
Owner Author

commented Aug 21, 2013

@braco It splits by . and then checks every segment individually, so will allow foo.bar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.