欧芹远程验证不会阻止表单提交

时间:2015-02-15 14:21:54

标签: angularjs validation parsley.js remote-validation

我正在使用带有angularJS的Parsley Remote验证。使用async验证器添加新的用户表单工作正常,它使用API​​并检查用户名是否已经存在,以及电子邮件,如果用户名它是否返回200状态,不等于404并显示错误消息..但是在提交表单时,如果我检查form.isvalid状态它返回true,它只验证NON远程选项。我被困在那里。

这是网络表单

<form class="form-horizontal form-label-left" method="post" id="AddUserForm"
            data-ui-jq="parsley"
            data-parsley-remote
            data-parsley-priority-enabled="false"
            novalidate="novalidate">
          <fieldset>
              <legend>
                  By default validation is started only after at least 3 characters have been input.
              </legend>
              <div class="form-group">
                  <label class="control-label col-sm-3" for="basic">User Name</label>
                  <div class="col-sm-9">
                      <input type="text" name="userName" class="form-control" data-ng-model="user.userName" value=""
                             data-parsley-remote
                             data-parsley-remote-validator='checkusername'
                             data-parsley-trigger="focusout"
                             data-parsley-remote-message="User name is already registerd in the system"
                             required="required" />

                      <span class="help-block">
                          Username must be unique
                      </span>
                  </div>
              </div>

              <div class="form-group">
                  <label class="control-label col-sm-3" for="email">
                      E-mail
                  </label>
                  <div class="col-sm-9">
                      <input type="email" id="email" name="email" class="form-control" data-ng-model="user.email"
                             data-parsley-remote
                             data-parsley-remote-validator='checkemail'
                             data-parsley-trigger="focusout"
                             data-parsley-remote-message="Email is already registerd in the system"
                             required="required" />
                      <span class="help-block">
                          Email must be unique
                      </span>
                  </div>
              </div>


              <div class="form-group">
                  <label class="control-label col-sm-3" for="password">
                      Password:
                  </label>
                  <div class="col-sm-9">
                      <input type="password" id="password" name="password" class="form-control mb-sm" data-ng-model="user.password"
                             data-parsley-trigger="change"
                             data-parsley-minlength="6"
                             required="required" />
                      <input type="password" id="password-r" name="password-r" class="form-control" placeholder="Confrim Password" data-ng-model="user.confirmPassword"
                             data-parsley-trigger="change"
                             data-parsley-minlength="6"
                             data-parsley-equalto="#password"
                             required="required" />
                  </div>
              </div>
          </fieldset>
          <div class="form-actions">
              <button type="submit" data-ng-click="AddNewUser($event)" class="btn btn-danger btn-rounded pull-right">Validate &amp; Submit</button>
              <button type="button" class="btn btn-default btn-rounded">Cancel</button>
          </div>
      </form>

这是我的异步验证器:

 window.ParsleyExtend = {
    asyncValidators: {
        checkusername: {
            fn: function (xhr) {
                console.log($('[name="userName"]'));
                return 404 === xhr.status;

            },
            url: authService.serviceBase + 'api/account/CheckUserName/' //+ $('[name="userName"]').text()


            },
        checkemail: {
            fn: function (xhr) {

                console.log($('[name="email"]')); 

                return 404 === xhr.status;
            },
            url: authService.serviceBase + 'api/account/CheckEmail/'// + $('[name="email"]').text()
        }
    }
};

这就是我验证表单的方式:

  $scope.AddNewUser = function ($event) {

    $event.preventDefault();
    //THis resturns true allways when the remote validation is not valid,, but when other non remote valdiation happens is works fine
    $('#AddUserForm').parsley().validate();
    //and this if statement  resturns true allways even when the remote validation is not valid,, but when other non remote valdiation happens is works fine
    if ($('#AddUserForm').parsley().isValid()) {
        authService.saveRegistration($scope.user).then(function (response) {

            $scope.savedSuccessfully = true;

            // $scope.message = "User has been registered successfully, you will be redicted to login page in 2 seconds.";
            //startTimer();

        },
         function (response) {
             var errors = [];
             for (var key in response.data.modelState) {
                 for (var i = 0; i < response.data.modelState[key].length; i++) {
                     errors.push(response.data.modelState[key][i]);
                 }
             }
             $scope.message = "Failed to register user due to:" + errors.join(' ');
         });
    }
};

2 个答案:

答案 0 :(得分:1)

刚刚找到答案..我必须使用asyncIsValid()和asyncValidate()以及普通的isValid()和Validate()方法..所以代码如下:

 $('#AddUserForm').parsley().asyncValidate();

if($('#AddUserForm').parsley().isValid() && $('#AddUserForm').parsley().isAsyncValid()) {

....}

答案 1 :(得分:0)

我首先检查每个字段以确保它已经过验证,如果字段未经过验证,我的ok变量将设置为false。

以下是一些示例代码:

$(function() {
  var ok;
  $('#signup').parsley().on('field:validated', function() {
      ok = $('.parsley-error').length === 0;
    })
    .on('form:submit', function() {
      if (ok) return true;
      else return false;
    });
});

Parsley.addAsyncValidator('checkExists', function(xhr) {
  return false === xhr.responseJSON;
}, '/data-management/verify-data?filter=signup');