Angluar 表单验证

疯云林渡
  • 271

小弟在做表单验证遇见了问题。
代码

<!DOCTYPE html>
<html lang="en" ng-app='app'>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        .error{color:#a10;}
    </style>
</head>
<body>
    <div class="container" ng-controller="Ctrl" >
        <form name='add' ng-submit="submit()" style="width:500px;margin:0 auto;padding:10px;">
            <h2>注册</h2>
            <div class="form-group">
                <label for="user">用户名</label>
                <input type="text" class="form-control user" ng-model="user" name='user' required ng-minlength="6" ng-maxlength="10" >
                <p class="error" ng-if="add.user.$error.required&&add.user.$touched" >用户名不能为空</p>
                <p class="error" ng-if="(add.user.$error.minlength||add.user.$error.maxlength)&&add.user.$touched">用户名长度不正确</p>
            </div>
            <div class="form-group">
                <label for="pwd">密码</label>
                <input type="password" class="form-control" ng-model="pwd" name='pwd' required ng-minlength="6" ng-maxlength="10"  >
                <p class="error" ng-if="add.pwd.$error.required&&add.pwd.$touched" >密码不能为空</p>
                <p class="error" ng-if="(add.pwd.$error.minlength||add.pwd.$error.maxlength)&&add.pwd.$touched">密码长度不正确</p>
            </div>
            <div class="form-group">
                <label for="user">确认密码</label>
                <input type="password" class="form-control user" ng-model="pwd2" requiredr name='pwd2' ng-minlength="6" ng-maxlength="10"  >
                <p class="error" ng-if="add.pwd2.$error.required&&add.pwd2.$touched" >确认密码不能为空</p>
                <p class="error" ng-if="(add.pwd2.$error.minlength||add.pwd2.$error.maxlength)&&add.pwd2.$touched">密码长度不正确</p>
            </div>
            <div class="form-group">
                <label for="user">性别</label>
                <select name="sex" id="" class="form-control" required>
                    <option value="">请选择</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                </select>
                <p class="error" ng-if="add.sex.$error.required&&add.sex.$touched" >性别不能为空</p>
            </div>
            <div class="form-group">
                <button class="btn btn-primary">提交</button>
            </div>
        </form>
    </div>
</body>
<script src='js/angular.js'></script>
<script>
    var app = angular.module('app',[]);
    app.controller('Ctrl',Ctrl);
    function Ctrl ($scope) {
        $scope.sub = {};
        $scope.submit = function(){
            console.log(1)
        }

    }
</script>
</html>

我发现输入框做验证都能显示。但到了select控件这的话。$touched,$error.require,$valid之内的验证指令都失效了。能问下是什原因吗?如果我需要做像输入框那样。如果没选择,或者选择了请选择这个选项我让错误提示出来呢?难道form表单验证值针对输入控件?

回复
阅读 2.3k
1 个回答

你没为select绑定数据嘛

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏