如何使用Angular jQuery Validate的checkForm()函数

时间:2017-02-21 23:00:54

标签: javascript jquery angularjs jquery-validate angular-validation

编辑:

I've added a JsFiddle因此您可以轻松排查故障,而无需自行设置环境。如您所见,甚至在blur元素上input事件发生之前,就会在电子邮件字段中进行验证,该事件由$scope.Email被更改触发。如果您在ng-show="!mainForm.validate()"元素上注释掉<p>,则会发现问题没有发生。

我正在使用Angular implementation of jQuery Validate,我需要能够在不显示错误消息的情况下检查表单是否有效。我在网上看到的标准解决方案是使用jQuery Validate的checkForm()函数,如下所示:

$('#myform').validate().checkForm()

但是,我正在使用的Angular包装器当前没有实现checkForm功能。我一直在尝试修改源代码以引入它,我担心我会在脑海中。代码很小很简单,我将它粘贴在这里:

(function (angular, $) {
    angular.module('ngValidate', [])

        .directive('ngValidate', function () {
            return {
                require: 'form',
                restrict: 'A',
                scope: {
                    ngValidate: '='
                },
                link: function (scope, element, attrs, form) {
                    var validator = element.validate(scope.ngValidate);

                    form.validate = function (options) {
                        var oldSettings = validator.settings;

                        validator.settings = $.extend(true, {}, validator.settings, options);

                        var valid = validator.form();

                        validator.settings = oldSettings; // Reset to old settings

                        return valid;
                    };

                    form.numberOfInvalids = function () {
                        return validator.numberOfInvalids();
                    };

                    //This is the part I've tried adding in.
                    //It runs, but still shows error messages when executed.
                    //form.checkForm = function() {
                    //  return validator.checkForm();
                    //}
                }
            };
        })

        .provider('$validator', function () {
            $.validator.setDefaults({
                onsubmit: false // to prevent validating twice
            });

            return {
                setDefaults: $.validator.setDefaults,
                addMethod: $.validator.addMethod,
                setDefaultMessages: function (messages) {
                    angular.extend($.validator.messages, messages);
                },
                format: $.validator.format,
                $get: function () {
                    return {};
                }
            };
        });
}(angular, jQuery));

我希望能够用它来显示或隐藏消息,如下所示:

<p class="alert alert-danger" ng-show="!mainForm.checkForm()">Please correct any errors above before saving.</p>

我不仅仅使用!mainForm.validate()的原因是因为这会导致错误消息在元素被“模糊”之前显示在元素上,这正是我想要避免的。任何人都可以帮我在这个角度指令中实现checkForm()函数吗?

6 个答案:

答案 0 :(得分:1)

您可以将checkForm()函数添加到插件中,如下所示。

    (function (angular, $) {
    angular.module('ngValidate', [])

        .directive('ngValidate', function () {
            return {
                require: 'form',
                restrict: 'A',
                scope: {
                    ngValidate: '='
                },
                link: function (scope, element, attrs, form) {
                    var validator = element.validate(scope.ngValidate);

                    form.validate = function (options) {
                        var oldSettings = validator.settings;

                        validator.settings = $.extend(true, {}, validator.settings, options);

                        var valid = validator.form();

                        validator.settings = oldSettings; // Reset to old settings

                        return valid;
                    };

                    form.checkForm = function (options) {
                        var oldSettings = validator.settings;

                        validator.settings = $.extend(true, {}, validator.settings, options);

                        var valid = validator.checkForm();

                        validator.submitted = {};

                        validator.settings = oldSettings; // Reset to old settings

                        return valid;
                    };

                    form.numberOfInvalids = function () {
                        return validator.numberOfInvalids();
                    };
                }
            };
        })

        .provider('$validator', function () {
            $.validator.setDefaults({
                onsubmit: false // to prevent validating twice
            });

            return {
                setDefaults: $.validator.setDefaults,
                addMethod: $.validator.addMethod,
                setDefaultMessages: function (messages) {
                    angular.extend($.validator.messages, messages);
                },
                format: $.validator.format,
                $get: function () {
                    return {};
                }
            };
        });
}(angular, jQuery));

请在此处找到更新的jsFiddle https://jsfiddle.net/b2k4p3aw/

参考:Jquery Validation: Call Valid without displaying errors?

答案 1 :(得分:0)

您可以使用ng-show="mainForm.Email.$invalid && mainForm.Email.$touched"<p>代码

来实现onblur事件

默认情况下mainForm.Email.$touchedfalse,在模糊时它会更改为true

正确验证会将<input>代码类型更改为电子邮件

如果您不想在编辑输入标记时显示错误消息,则可以添加ng-keydown="mainForm.Email.$touched=false"

我没有使用angular-validate.js插件

<div ng-app="PageModule" ng-controller="MainController" class="container"><br />
  <form method="post" name="mainForm" ng-submit="OnSubmit(mainForm)" >
    <label>Email: 
      <input type="email" name="Email" ng-keydown="mainForm.Email.$touched=false" ng-model="Email" class="email" />
    </label><br />
    <p class="alert alert-danger" ng-show="mainForm.Email.$invalid && mainForm.Email.$touched">Please correct any errors above before saving.</p>
    <button type="submit">Submit</button>
  </form>
</div>

更新了代码:JSFiddle

AngularJs Form Validation

More info on Angular validation

更新2

checkForm将返回表单是有效还是无效

// added checForm, also adds valid and invalid to angular
form.checkForm = function (){
    var valid =  validator.form();

    angular.forEach(validator.successList, function(value, key) {
     scope.$parent[formName][value.name].$setValidity(value.name,true);
    });

    angular.forEach(validator.errorMap, function(value, key) {
      scope.$parent[formName][key].$setValidity(key,false);
    });

    return valid
}

隐藏默认邮件,将jQuery验证插件添加到以下代码段,添加到$.validator.setDefaults

app.config(function ($validatorProvider) {
    $validatorProvider.setDefaults({
        errorPlacement: function(error,element) { // to hide default error messages
              return true;
           }
    });
});

这里修改后的插件看起来像

(function (angular, $) {
angular.module('ngValidate', [])

    .directive('ngValidate', function () {
        return {
            require: 'form',
            restrict: 'A',
            scope: {
                ngValidate: '='
            },
            link: function (scope, element, attrs, form) {
                var validator = element.validate(scope.ngValidate);
                var formName = validator.currentForm.name;

                form.validate = function (options) {
                    var oldSettings = validator.settings;

                    validator.settings = $.extend(true, {}, validator.settings, options);

                    var valid = validator.form();

                    validator.settings = oldSettings; // Reset to old settings

                    return valid;
                };

                form.numberOfInvalids = function () {                           
                    return validator.numberOfInvalids();
                };

                // added checkForm
                form.checkForm = function (){
                    var valid =  validator.form();

                    angular.forEach(validator.successList, function(value, key) {
                     scope.$parent[formName][value.name].$setValidity(value.name,true);
                    });

                    angular.forEach(validator.errorMap, function(value, key) {
                      scope.$parent[formName][key].$setValidity(key,false);
                    });

                    return valid
                }
            }
        };
    })

    .provider('$validator', function () {
        $.validator.setDefaults({
            onsubmit: false // to prevent validating twice            
        });

        return {
            setDefaults: $.validator.setDefaults,
            addMethod: $.validator.addMethod,
            setDefaultMessages: function (messages) {
                angular.extend($.validator.messages, messages);
            },
            format: $.validator.format,
            $get: function () {
                return {};
            }
        };
    });
  }(angular, jQuery));

控制器

app.controller("MainController", function($scope) {
$scope.Email = "";
$scope.url = "";
$scope.isFormInValid = false; // to hide validation messages
$scope.OnSubmit = function(form) {
    // here you can determine
    $scope.isFormInValid = !$scope.mainForm.checkForm(); 

     return false; 
 }
 })

需要对每个输入标记(电子邮件示例)

进行跟踪
ng-show="isFormInValid && !mainForm.Email.$invalid "

如果表单和电子邮件都无效,则会显示验证消息。

JSFiddle

答案 2 :(得分:0)

如果我正确理解您的问题,您希望能够在电子邮件地址无效并且您决定要显示错误消息时显示错误消息。

您可以通过将输入类型设置为电子邮件(例如<input type=email>

来实现此目的

Angular在表单$valid中添加了一个属性,因此您可以在控制器中检查提交的文本是否有效。所以我们只需要在控制器中访问这个变量并将其反转。 (因为我们想在无效时显示错误)

$scope.onSubmit = function() {
    // Decide here if you want to show the error message or not
    $scope.mainForm.unvalidSubmit = !$scope.mainForm.$valid
}

我还添加了一个提交按钮,该按钮在提交时使用浏览器验证。这样,onSubmit函数甚至不会被调用,浏览器将显示错误。除angularjs外,这些方法不需要任何其他方法。 您可以查看更新的JSFiddle here

确保打开控制台以查看调用onSubmit函数的时间以及按下按钮时发送的值。

答案 3 :(得分:0)

您可以使用 $ touch ,只要字段聚焦然后模糊,就会为真。

 <p class="alert alert-danger" ng-show="mainForm.Email.$touched && !mainForm.validate()">Please correct any errors above before saving.</p>

答案 4 :(得分:-1)

尝试此代码进行验证,这是表格

    <form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
    <div class="form-group">   
    <input  type="text"  ng-class="{ 'has-error' : userForm.name.$invalid &&    !userForm.name.$pristine }" ng-model="name" name="name" class="form-control" placeholder="{{ 'regName' | translate }}" required>
  <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">Your name is required.</p>

  </div>

<div class="form-group">
  <input  type="tel" ng-class="{ 'has-error' : userForm.mob.$invalid && !userForm.mob.$pristine }" ng-model="mob" class="form-control" name="mob" ng-maxlength="11" ng-minlength="11"  ng-pattern="/^\d+$/"  placeholder="{{ 'regPhone' | translate }}" required>
       <p ng-show="userForm.mob.$invalid && !userForm.mob.$pristine" class="help-block">Enter a valid number</p>

  </div>
  <div class="form-group">
  <input  type="email"  ng-model="email" name="email" class="form-control" placeholder="{{ 'regEmail' | translate }}"   required>

<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>

<div class="form-group">
  <input   type="password" ng-model="pass" name="pass"  class="form-control" placeholder="{{ 'regPass' | translate }}" minlength="6" maxlength="16" required>
  <p ng-show="userForm.pass.$invalid && !userForm.pass.$pristine" class="help-block"> Too short Min:6 Max:16</p>


  <input  type="password" ng-model="repass"  class="form-control" ng-minlength="6" placeholder="{{ 'regConPass' | translate }}" ng-maxlength="16" required>
  </div>
 <button class="loginbtntwo" type="submit" id="regbtn2"  ng-disabled="userForm.$dirty && userForm.$invalid" translate="signUp" ></button>
  </form>

答案 5 :(得分:-1)

您需要稍微修改Angular Validate Plugin。以下是JSFiddle中代码的工作版本。请注意更新的插件代码以及对原始代码的一对修改。

更新的插件代码只是将其添加到validator.SetDefaults参数:

errorPlacement: function(error,element) { return true; } // to hide default error message

然后我们使用范围变量来隐藏/显示自定义错误消息:

$scope.OnSubmit = function(form) {
if (form.$dirty) {
    if (form.validate()) {
    //form submittal code
    } else {
    $scope.FormInvalid = true;
  }
}