原始时表单上未显示错误消息

时间:2016-06-26 01:03:00

标签: angularjs

我有以下代码进行表单验证。当我在文本框中输入一些值(脏)并且值无效时,它会显示错误消息。但是当我不进行任何更改(原始)并单击“提交”时,不会显示错误消息。如何在这种情况下触发错误消息?

注意:当我删除原始检查时,即使在提交之前也会显示错误消息。



<!DOCTYPE html>
<html>
<head>
    <!-- bootstrap -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <style>
        body{padding-top: 30px;}
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-resource.js"></script>
    
    <script type="text/JavaScript">

        var myApp = angular.module('myApp', []);
        
        myApp.controller('myController', function ($scope) {

            //Call function on form submit
            $scope.submitForm = function (isValid) {

                if (isValid) {
                    alert('Valid');
                }
                else {
                    alert('Invalid');
                }

            };

        });

    </script>
</head>
<body ng-app="myApp" ng-controller="myController">
    <div class="myDiv">
        <div class="col-sm-8 col-sm-offset-2">
            <div class="page-header">
                <h1>Validation</h1>
            </div>
            <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
            <!-- Prevents HTML5 validation using novalidate-->
            
            
            <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
                <label>Name</label>
                <input type="text" name="name" class="form-control" ng-model="user.name" required>
                <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">
                    Name required.</p>
            </div>

            
            <div class="form-group" ng-class="{ 'has-error' : userForm.location.$invalid && !userForm.location.$pristine }">
                <label>Location</label>
                <input type="text" name="location" class="form-control" ng-model="user.location"
                    ng-minlength="3" ng-maxlength="8">
                <p ng-show="userForm.location.$error.minlength" class="help-block">
                    Location is less than min length.</p>
                <p ng-show="userForm.location.$error.maxlength" class="help-block">
                    Location more than max length.</p>
            </div>

            <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
        
    </div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

尝试使用userForm.$submitted代替$pristine

要进行良好的学习练习和调试,请在视图中尝试以下内容

<pre>{{userForm|json}}</pre> 
相关问题