8

编辑:

我添加了一个 JsFiddle,因此您可以轻松排除故障,而不必自己设置环境。如您所见,甚至在元素上的blur事件之前就已在电子邮件字段上完成验证,该事件是由被更改触发的。如果您注释掉元素上的,您会发现问题没有发生。input$scope.Emailng-show="!mainForm.validate()"<p>


我正在使用jQuery Validate 的 Angular 实现,并且我需要能够在不显示错误消息的情况下检查表单是否有效。我在网上看到的标准解决方案是使用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()这个角度指令中实现这个功能?

4

6 回答 6

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:调用有效而不显示错误?

于 2017-03-13T00:46:56.250 回答
0

您可以使用$touched,只要字段聚焦然后模糊就可以了。

 <p class="alert alert-danger" ng-show="mainForm.Email.$touched && !mainForm.validate()">Please correct any errors above before saving.</p>
于 2017-03-01T16:03:56.943 回答
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

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

于 2017-02-24T23:48:55.540 回答
0

ng-show="mainForm.Email.$invalid && mainForm.Email.$touched"您可以使用to<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 表单验证

有关 Angular 验证的更多信息


更新 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

于 2017-02-24T23:40:38.693 回答
-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>
于 2017-02-25T13:04:23.633 回答
-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;
  }
}
于 2017-03-02T12:02:08.967 回答