Skip to content

Instantly share code, notes, and snippets.

@Daniel15
Created July 9, 2012 05:26
Show Gist options
  • Save Daniel15/3074365 to your computer and use it in GitHub Desktop.
Save Daniel15/3074365 to your computer and use it in GitHub Desktop.
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
Copy link

braco 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
Copy link
Author

@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