ANGULARJS - 仅在提交时进行验证

时间:2015-02-18 14:59:45

标签: javascript angularjs validation

我想在提交时进行验证。现在,我已经为输入创建了一个指令,检查最小值是否为5000,但我不希望它检查我通过按键输入的每个数字。我只想在检查提交时检查它。 这是:http://jsfiddle.net/58b7491d/

HTML

<div ng-app="myAppApp">
  <div ng-controller="MainCtrl">
        <form name="myForm" novalidate ng-submit="submitPlanInfo(myForm.$valid);">
            <div>
                <label for="initInvestment">Number (Min: 5000)</label>
                <input id="initInvestment" name="initInvestment" class="form-control" ng-model="model1.InitInvestment" required min-Value="5000"/>
                <p ng-show="myForm.initInvestment.$invalid && myForm.initInvestment.$dirty && myForm.$submitted" class="validation">Min Value should be 5000</p>

            </div>
            <div>
                <button type="submit" name="submit">Submit</button>
            </div>
        </form>
    </div>
</div>

JAVASCRIPT

angular.module('myAppApp', [])
.directive('minValue', function () {
    return {
        require: "ngModel",
        restrict: 'A',
        link: function postLink(scope, element, attrs, ngModel) {

            ngModel.$validators.minValueErrMsg = function (value) {
                var status = true;
                console.log(value);
                if (value < attrs.minValue) {
                    status = false;
                }
                return status;
            };
        }
    };
})
.controller('MainCtrl', function ($scope, $controller) {
    //LETS DO THE FORM VALIDATION AFTER HITTING SUBMIT!!
    $scope.submitPlanInfo = function (isValid) {
        console.log($scope.myForm);
        if ($scope.myForm.$valid) {
            console.log($scope.myForm.initInvestment);
           // console.log(angular.isNumber(parseInt($scope.myForm.initInvestment.$modelValue)));
            var minVal = parseInt($scope.myForm.initInvestment.$modelValue);
           // console.log(angular.isNumber(minVal));
            if (minVal < 5000){
                console.log("should be min 5000");
                return false;
            }else{
                console.log("success");
                return true;
            }
            alert("Valid");
        }

    };
    //END OF FORM VALIDATION
});

1 个答案:

答案 0 :(得分:1)

提交后IMO验证不是一个非常好的用户体验。我会尝试使用ng-messages指令并设置ng-model-options来更新blur

Consider reading year of moo's post about this

他深入研究了同步和异步验证器,以及ng-model-options上的一小部分。

Angular docs - ngModelOptions

Angular docs - ngMessages