Validating input parameters in JavaScript

Source: Internet
Author: User
Javascript

The list of parameters in a JavaScript function declaration doesn't mean anything ... They are purely for the convenience of accessing these parameters, and there is no limit to how the caller passes the arguments, how the caller wants to pass it, as long as the script is not wrong ...

All, sometimes in order to ensure the robustness of the program, we need to implement the validation of input parameters and the default input parameters. These days the process of learning just write a few simple solutions, put here to do backup.

The first is the legality of the authentication type:


function Validatetype (obj, type) {
if (!) ( obj instanceof type)) {
throw new Error ("Invalid type of the argument of" + Arguments.callee.caller);
}

return true;
}


Then verify that the parameter values are valid:


function Validatevalue (obj, Vfunc) {
Validatetype (Vfunc, Function); Vfunc must be Function object
if (!vfunc (obj)) {
throw new Error ("Invalid value of the argument of" + Arguments.callee.caller);
}
}


Again, the default parameter, if the parameter is undefined (that is, no parameters are passed), then the specified default parameter is used:


function Setdefaultvalue (param, defval) {
var undefined;

if (undefined = = param) {
return defval;
} else {
return param;
}
}


OK, that's all. Can be added later, do what you need to do it ~
They are very simple to use. For example, function add, assuming that the incoming must be a positive number, and B can not pass, the default is 10:


function Add (A, b) {
var adder = Setdefaultvalue (b, 10);

Validatetype (A, number);
Validatetype (adder, number);
Validatevalue (A, function (n) {return n > 0 true:false;});
Validatevalue (adder, function (n) {return n > 0 true:false;});

return a + adder;
}


Well, JavaScript is really fun!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.