输入字段有效后清除错误

时间:2017-03-05 07:49:12

标签: javascript html angularjs node.js

我将AngularJS与node.js一起使用。我已经实现了错误处理程序,如下所示:

node router effect.js:

router.post('/', function(req, res, next){

    req.checkBody('name', 'Effect name is required.').notEmpty();
    var errors = req.validationErrors();

    console.log(errors);

    if(errors) {
        res.status(500).json(errors);
        return;
    }

    var effect = new Effect({
        name: req.body.name
    });

    Effect.createEffect(effect, function(err, result) {
        if(err) { next(err) }
        res.status(201).end();
    });

});

effectController.js:

$scope.submit = function(effect) {

    effectService.save(effect, function(err, result, status) {

        $scope.errors = err;

        if(err == null) {
            $scope.effect = null;
            if(!(effect == null || effect == undefined)) {
                if(!(effect._id == undefined || effect._id == '')) { 
                    $location.path('/effect');
                }
            }
            reload();
        }

    });

}

effectService.js

function save(effect, callback) {
    if(effect == undefined || effect._id == undefined || effect._id == '') {
        $http.post('/api/effect', effect)
             .success(function(data, status) {
                callback(null, data);
             })
             .error(function(data, status) {
                var errors = {};
                for (var i = 0; i < data.length; i++) {
                    var err = data[i];
                    var param, msg;
                    for(var key in err){
                        if(key == 'param') param = err[key];
                        if(key == 'msg') msg = err[key];
                    }
                    errors[param] = msg;
                }
                callback(errors, null);
             });
    } else {
        $http.put('/api/effect/' + effect._id, effect);
    }
}

HTML:

<form novalidate>
    <div class="form-group">
        <label for="name" class="form-label">Name</label>
        <div class="col-xs-12" ng-class="{ 'has-error': errors.fname }">
            <input type="text" id="name" name="name" class="form-control form-input" ng-model="effect.name"
                   ng-disabled="isReadOnly" required />
            <p class="help-block" ng-model="errors.name" ng-show="(errors == null || errors == undefined) ? false : errors.name">Effect name is required</p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <div class="form-group form-controls">
                <button id="submit" class="btn btn-success btn-input submit" ng-click="submit(effect)" ng-hide="isReadOnly">Save</button>
                <button id="clear" class="btn btn-input clear" ng-class="isReadOnly ? 'btn-primary' : 'btn-danger'" ng-click="clear()">{{clearButtonText}}</button>
            </div>
        </div>
    </div>
</form>

- &GT;这可以按预期工作。

问题:

当服务器出错时,页面上会显示错误。但只要输入有效,错误就不会消失。简而言之,我希望输入字段有效后错误就会消失。我不希望用户点击提交按钮来清除错误。

更新

我已在服务器中为重复项实现了另一个验证,如下所示:

index.js文件:

app.use(expressValidator({
    customValidators: {
        duplicateRecord: function(input, propertyName, collection) {
            var duplicateRecordFound = false;
            collection.forEach(function(element) {
                if (element.propertyName == input) {
                    duplicateRecordFound = true;
                    return;
                }
            }, this);
            return duplicateRecordFound;
        }
    }
}));

路由器effect.js文件:

router.post('/', function(req, res, next){

    Effect.find(function(err, effects) {

        if(err){
            next(err);
        }

        req.checkBody('name', 'Effect name is required.').notEmpty();
        req.checkBody('name', 'Duplicate effect name.').duplicateRecord('name', effects);
        var errors = req.validationErrors();

        console.log(errors);

        if(errors) {
            res.status(500).json(errors);
            return;
        }

        var effect = new Effect({
            name: req.body.name
        });

        Effect.createEffect(effect, function(err, result) {
            if(err) { next(err) }
            res.status(201).end();
        });

    });

});

我还改变了@lean建议的角度控制器:

$scope.validate = function () {
    if($scope.errors != undefined)
    {
        if (angular.isDefined($scope.effect.name) && $scope.effect.name.length > 0) {
            $scope.errors.showName = false;
        } else {
            $scope.errors.showName = true;
        }
    }
}

$scope.submit = function(effect) {

    effectService.save(effect, function(err, result, status) {

        $scope.errors = err;

        if(err == null) {
            $scope.effect = null;
            if(!(effect == null || effect == undefined)) {
                if(!(effect._id == undefined || effect._id == '')) { 
                    $location.path('/effect');
                }
            }
            reload();
        } else {
            $scope.errors.showName = true;
        }

    });

我还改变了html文件中的段落元素,如下所示:

<input type="text" id="name" name="name" class="form-control form-input" ng-model="effect.name"
       ng-change="validate()" ng-disabled="isReadOnly" required />
<p class="help-block" ng-model="errors.name" ng-show="(errors == null || errors == undefined) ? false : (errors.showName)">{{errors.name}}</p>

问题:

当我在输入中输入效果的名称然后单击提交按钮时,如果效果的名称已经存在于数据库中,那么我会收到一条消息Duplicate Effect name。然后,如果我更改输入框中的字符,则错误消息消失。到目前为止,它工作正常。但是如果我删除输入框中的所有文本,则显示的错误消息再次是Duplicate Effect name.而不是Effect name is required.

1 个答案:

答案 0 :(得分:0)

您可以在输入中使用ng-change来调用此示例中的validate()等验证程序函数。

视图

<form novalidate>
    <div class="form-group">
        <label for="name" class="form-label">Name</label>
        <div class="col-xs-12" ng-class="{ 'has-error': errors.name }">
            <input type="text"
                   id="name"
                   name="name"
                   class="form-control form-input"
                   ng-model="effect.name"
                   ng-change="validate()"
                   ng-disabled="isReadOnly" 
                   required />
            <p class="help-block" ng-model="errors.name" ng-show="(errors == null || errors == undefined) ? false : errors.name">Effect name is required</p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <div class="form-group form-controls">
                <button id="submit" class="btn btn-success btn-input submit" ng-click="submit(effect)" ng-hide="isReadOnly">Save</button>
                <button id="clear" class="btn btn-input clear" ng-class="isReadOnly ? 'btn-primary' : 'btn-danger'" ng-click="clear()">{{clearButtonText}}</button>
            </div>
        </div>
    </div>
</form>

验证$ scope函数

//init scopes
$scope.errors = {};
$scope.effect = {
  name: ''
}

/**
 * Manually validate fields
 */
$scope.validate = function () {
    if (angular.isDefined($scope.effect.name) && $scope.effect.name.length > 0) {
        $scope.errors.name = false;
    } else {
        $scope.errors.name = true;
    }
}