Validate function parameters in JavaScript

JavaScript is not so well structured like other languages (C#, Java). When you define a variable like this

var myVariable;

You do not specify type of variable. It can be string, object, array or other JavaScript type. So, passing variable to a function can a problem as very easy you can pass a type which is not accepted by the function. But, ASP.NET Ajax is offering a way to validate parameters. Consider the code below:

function DoSomething(expectedVariable) {
	var e = Function._validateParams(arguments, [{ name: "expectedVariable", type: String }], true);
 	if (e) {  throw e; }

Code above is checking is if parameter passed to DoSomething function is a string and stop code execution if condition is not true, throwing an error. Other types can be also checked: Object, Array, Function. You can also specify if parameter is option or if it can be null.

If you are asking from where Function._validateParams comes from, you can check ASP.NET AJAX JavaScript library. It was supposed to be used internally (“-“ sign, by convention, means property or method is private), but without no issues you can use it directly in your code. If you have version 4 of the library, Microsoft included also a public version of this called “Function.validateParameters”. Please find official reference here.

About these ads

About anvlpopescu

Nothing special to say. I'll think about it more and let your know.
This entry was posted in ASP.NET Ajax, JavaScript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s