简体   繁体   中英

jquery validation is not working with templates inside ng view

Simply I'm using JQuery validation to validate this simple form

<form id="getting-started-form">
<label>Name</label>
<input type="text" id="txt-name" name="name" />

<br />
<label>Email</label>
<input type="text" id="txt-email" name="email" />

<button type="submit">Validate</button>
</form>

the validation works fine if this form is not is not included inside ng view , however when I retrieve this template using the ng route , the validation is not working with the same form .

this is my simple HTML page

<!DOCTYPE html>
<html data-ng-app="ngViewValidate">
<head>
<title></title>
</head>
<body>

<div data-ng-view="">
</div>

<br />
<a href="#/ValidationTmpl">Go to validation template </a>
</body>
<script src="../Scripts/angularjs.js"></script>
<script src="../Scripts/angular-route.js"></script>
<script src="../Scripts/jquery-2.0.2.js"></script>
<script src="../Scripts/jquery.validate.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.js"></script>
<script src="JQueryValidateWithNgView.js"></script>
</html>

and this is my java script file JqueryValidateWithNgView

var ngViewValidate = angular.module('ngViewValidate', ['ngRoute']);

ngViewValidate.config(function ($routeProvider , $locationProvider) {

$routeProvider.when('/ValidationTmpl',
    {
        templateUrl: '/WithAngular/ValidationTmpl.html'
    })
})

$('#getting-started-form').validate({

rules: {
    name: {
        required: true
    },
    email: {
        required: true
    }
},
submitHandler: function (form) {
    console.log('Valid');
},
invalidHandler: function (event, validator) {
    console.log('InValid');
}
})

the question is can I use JQuery validation with templates inside ng view using any work around , or should I use the angular validation ?

I created a bridge between AngularJS and the jQuery Validation Plugin. It validates a form using a single directive ng-validate , which automatically detects when the DOM is ready. It also gives you the ability to define your validation options (rules, messages, etc.) inside your controller, so you don't have to create a new directive for each form.

Give it a try: https://github.com/jpkleemans/angular-validate . Feedback is highly appreciated!

Move it into a directive and for example put it on the form.

HTML:

<form id="getting-started-form" j-validate>

JS:

ngViewValidate.directive('jValidate', function() {

  return {
    link: function(scope, element, attr) {

      element.validate({

        rules: {
          name: {
            required: true
          },
          email: {
            required: true
          }
        },
        submitHandler: function(form) {
          console.log('Valid');
        },
        invalidHandler: function(event, validator) {
          console.log('InValid');
        }
      });

      scope.$on('$destroy', function () {
        // Perform cleanup.
        // (Not familiar with the plugin so don't know what should to be done)
      });
    }
  }
});

Demo: http://plnkr.co/edit/cjQH7dl3vHGzgaA9OHOy?p=preview

Depending on the logic you are going to put in the directive, for example if you need additional jQuery plugins to modify the form before binding, you can use $timeout without a delay to (a bit simplified) put the action at the end of the browser event queue after the rending engine:

ngViewValidate.directive('jValidate', function($timeout) {

  return {
    link: function(scope, element, attr) {

      $timeout(function () {

        element.validate({

          ...

        });
      });

      scope.$on('$destroy', function() {

        ...

      });
    }
  }
});

Alternatively you can use $evalAsync to perform the logic after the DOM has been manipulated by Angular, for example by other directives, but before the browser renders it:

ngViewValidate.directive('jValidate', function() {

  return {
    link: function(scope, element, attr) {

      scope.$evalAsync(function () {

        element.validate({

          ...

        });
      });

      scope.$on('$destroy', function() {

        ...

      });
    }
  }
});

The simplest way to get tis to work is

   $scope.$on('$viewContentLoaded', function (event) {


            var currentForm = $('#frmCreateForm');
            currentForm.removeData("validator");
            currentForm.removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse(currentForm);
            //currForm.validate();
            var validator = currentForm.validate();  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM