在angularjs中进行表单验证和提交

时间:2014-08-20 10:34:10

标签: html angularjs forms validation

我有html文件:

<form role="form"  ng-submit="resetPasswordRequest();" name="resetPasswordForm" novalidate>


    <div  ng-show="!sessionExpired">

          <input type="password" ng-model="password" ng-focus  placeholder="New Password" name ="password" autofocus   ng-minlength="5" ng-maxlength="20"  required />
              <span  ng-show="resetPasswordForm.password.$error.required && submitted">New Password Required</span><br>
              <span  ng-show="resetPasswordForm.password.$error.minlength">New Password should contain at least 5 characters </span><br>
              <span  ng-show="resetPasswordForm.password.$error.maxlength">New Password  maximum length up to 20  characters only </span><br>


          <input type="password" ng-model="resetPassword" ng-focus  placeholder="Retype Password" name ="resetPassword" id ="resetPassword" autofocus  required/>
              <span  ng-show="resetPasswordForm.resetPassword.$error.required && submitted">Retype Password Required</span><br>
              <span ng-show="!resetPasswordForm.resetPassword.$error.required && resetPassword != password && submitted">Password not matching</span><br>

        <br><button type="submit" class="login-btn" ng-click="submitted=true">SUBMIT</button><br>
    </div>
    <div  ng-show="sessionExpired">
        <p class="txt-bld error-message" >URL Expired</p>
    </div>
</form>

我有控制器:

$scope.resetPasswordRequest = function(){
//valid form submission  only process the logic
if($scope.resetPasswordForm.$valid){ //some logic }
}
用上面的表格我可以验证表格密码字段minlength,maxlenth,empty,但是密码问题和重新输入密码数据匹配的情况。  <span ng-show="!resetPasswordForm.resetPassword.$error.required && resetPassword != password && submitted">Password not matching</span>

即使通过密码和重新输入密码的数据也不匹配提交的表单并调用控制器功能并处理控制器逻辑。 但是如果表单中缺少任何验证然后重新键入和密码数据匹配大小写正常工作,如果没有发生验证(最小,最大长度,空)(表格中的所有内容都是正例)密码并重新输入密码数据匹配无效。

我如何验证表单密码并重新键入密码数据,如min length,max length属性和out external指令。

1 个答案:

答案 0 :(得分:0)

您可以创建一个简单的指令来检查密码是否匹配。从指令返回的结果中,您可以设置第二个密码字段的有效性。

示例HTML

<input type="password" id="password1" name="password1" ng-model="password1" required/>
<input type="password" id="password2" name="password2" ng-model="password2" required check-passwords="password1" />

示例JS

ngAppModule.directive('checkPasswords', [function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attributes, ctrl) {

            // get the value of the attribute. In this case, it will be "password1"
            var firstPwd = '#' + attributes.checkPasswords;
            element.add(firstPwd).on('keyup', function () {
                scope.$apply(function () {
                    var isValid = element.val() === $(firstPwd).val();
                    // use "pwdsMatch" in "ng-show" along with the other validations
                    ctrl.$setValidity('pwdsMatch', isValid);
                });
            });
        }
    };
}]);