角度自定义表单验证的好策略是什么?

时间:2014-05-06 19:58:40

标签: javascript angularjs validation

随着我的应用程序不断增长,我发现需要更有效的表单验证。我个人不喜欢角度内置验证,评估场变化。并且总有一些事情可以解决,例如验证YouTube视频ID是否有效。目前我正在每个表单控制器中进行验证。我有一个看起来像这样的功能。每个字段都有一条消息,如果有错误,消息将使用ng-class显示为红色。

$scope.validate = function (callback) {

    // reset default messages
    setMessages();

    // create shorter references
    var item = $scope.item,
        message = $scope.itemMessage;

    // title exists
    if (item.title === '') {
        message.title.message = 'You must give your item a title.';
        message.title.error = true;
        message.errors += 1;
    }

    // extract and clear video id with youtube api
    if ($scope.temp.video !== undefined && $scope.temp.video !== '') {

        var id = '';
        var url = $scope.temp.video.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);

        if(url[2] !== undefined) {
            id = url[2].split(/[^0-9a-z_]/i);
            id = id[0];
        } else {
            id = url;
        }

        $http.get("http://gdata.youtube.com/feeds/api/videos/" + id)
            .then(function (res) {
                $scope.item.video = id;
            }, function (res) {
                message.video.message = 'That is not a valid youtube video.';
                message.video.error = true;
                message.errors += 1;
                $scope.item.video = '';
            });
    }

    if (message.errors === 0) {
        callback();
    }

};

然后我的实际表单提交函数调用$ scope.validate();传递一个包含$ http.post()的函数。我看到的两个主要问题是我的回调不是基础,所以当错误存在并且我一次又一次地读取以保持较大时,不能保证它不会被调用控制器外部的逻辑块。我还没有找到应该如何做的很好的例子,但它必定是一个常见的问题。

1 个答案:

答案 0 :(得分:0)

您仍然可以使用Angular的内置验证,除非已提交表单,否则不进行评估:

http://scotch.io/tutorials/javascript/angularjs-form-validation#only-showing-errors-after-submitting-the-form

基本上,您在提交表单时设置$scope.submitted = true并设置条件检查,以便仅在设置$scope.submitted时显示错误消息和类。

相关问题