Demystifying The Code

AJAX Q & A Question 4 – In methods, how do I validate types of passed parameters?

ASP.NET AJAX has extended Function with a "private" static method called _validateParams for this purpose.  The _validateParams method is used throughout the ASP.NET AJAX client library to validate arguments/parameters.  You are free to use this in your code to validate parameters.  The following is a copy of the documentation for the private method.:

// <summary>
//     Validates the parameters to a method.
// </summary>
// <example>
//     function foo(anyParam, stringParam, anyArrayParam, stringArrayParam,
//                  interfaceParam, optionalStringParam) {
//         #if DEBUG
//         var e = Function._validateParams(arguments, [
//             { name: "anyParam" },
//             { name: "mayBeNullParam", mayBeNull: true },
//             { name: "stringParam", type: String },
//             { name: "floatParam", type: Number },
//             { name: "intParam", type: Number, integer: true },
//             { name: "domParam", domElement: true },
//             { name: "anyArrayParam", type: Array },
//             { name: "mayBeNullArrayParam", type: Array, elementMayBeNull: true },
//             { name: "stringArrayParam", type: Array, elementType: String },
//             { name: "intArrayParam", type: Array, elementType: Number, elementInteger: true },
//             { name: "domElementArrayParam", type: Array, elementDomElement: true },
//             { name: "interfaceParam", type: Sys.IFoo }
//             { name: "optionalStringParam", type: String, optional: true }
//             { name: "stringParamArray", type: String, parameterArray: true }
//             { name: "mayBeNullParamArray", parameterArray: true, mayBeNull: true }
//         ]);
//         if (e) throw e;
//         #endif
//     }
// </example>
// <param name="params" type="Array">Array of parameter values passed to the method.</param>
// <param name="expectedParams" type="Array" optional="true">Array of JSON objects describing the expected parameters.</param>

Here is an example.  In the setter for LastName, we are validating to make sure that a string is passed:

 ValidateParam

Here you can see we try to set a string, which is successful, then we try to pass a bool, which will fail validation.

CallingParam

Here you can see the message of the error that was thrown:

Error

Notice that you can also validate that the param implements a certain interface.  here are some screenshots illustrating that:

INterfaceValidate

Calling code:

InterfaceCall

Error:

InterFaceError

Want to add a question to the list?  Email me at rob.bagby@microsoft.com.

Regards

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

Demystifying The Code