【问题标题】:JavaScript argument validationJavaScript 参数验证
【发布时间】:2015-03-22 16:49:48
【问题描述】:

我正在编写一个来自 PHP 背景的 Angular 应用程序。我想知道是否有任何好的断言/验证库可以用来帮助我验证传递给我的模型的参数,例如Validate.isNumber(data.id) 并在失败时自动抛出适当的异常

app.factory('Something', ['moment', function(moment){

    function Something(data) {

        // validate data has required properties and they are of the expected type!!!

        this.id = data.id;
        this.title = data.title;
        this.description = data.description;
    }

    Something.prototype.getId = function () {
        return this.id;
    };

    Something.prototype.getTitle = function () {
        return this.title;
    };

    Something.prototype.getDescription = function () {
        return this.description;
    };

    return Something;

}]);

【问题讨论】:

    标签: javascript angularjs validation


    【解决方案1】:

    我个人使用这个 JSON-Validator tv4:

    https://github.com/geraintluff/tv4

    它依赖于您提供的架构来告诉它您传递的参数(JSON 结构)必须如何形成以及允许使用哪种类型。

    在这里您可以找到它支持的所有验证选项:

    http://json-schema.org/latest/json-schema-validation.html

    在这里你找到一个实用的example

    【讨论】:

    • 不客气,我已经在一个项目中使用过它,它确实做到了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多