jonsamwell/angular-auto-validate

Manually trigger form validation

Closed this issue · 7 comments

Hey guys,

After spending some time looking for this I come to you. Some of my forms do not define a ng-submit call to action but a simple link with a ng-click. From the controller, I would like to be able to trigger the form validation. Any idea how I can do that?

Thx

Hi @gottfrois,

This can be done quite easily via the validationManager. You can have a look at the form reset directive which contains the code you will need but apart from calling reset form you will need to call validateForm passing in the form element.

This is the method you need to call on the validationManager passing in the form you wish to validate:
https://github.com/jonsamwell/angular-auto-validate/blob/master/src/services/validationManager.js#L135

This is the reset directive:
https://github.com/jonsamwell/angular-auto-validate/blob/master/src/directives/formReset.js#L16

Jon

Ah i see, suddenly it all make sense :) Thx

I am trying to trigger validation from the controller but not from ng-submit, I have injected the validation manager in my controller as follows:
angular.module('MyModule').controller('MyController', ['validationManager', function (validationManager) { $scope.validateForm=function(){ validationManager.validateForm($scope.myForm) } });
It gives me the following error:
Cannot read property 'autoValidateFormOptions' of undefined
@gottfrois @jonsamwell Am I doing something wrong?

Hi @yassm

The validateForm method takes in a form element I would assume that $scope.myForm is a controller?

https://github.com/jonsamwell/angular-auto-validate/blob/master/src/services/validationManager.js#L144

Hi @jonsamwell
Thank you for your help, $scope.myForm is the form not a controller,
I have my HTML form like:
<form name="myForm">
and access it from the controller like this:
$scope.myForm
I actually do the following, to check if form is valid

if($scope.myForm.$valid){
console.log('form is valid');
}
else{
console.log('form has errors');
}

it works well for validation, but it does not change the styles of the inputs.

Hi @yassm

The $scope.myForm is the form controller not the form element. The validation manager need the form element not the form controller. So without passing the actual element into the validationManager.validateForm method it will not change the styles.

Thanks a lot @jonsamwell
and sorry for inconvenience, I managed to do it through you guidance, I passed the form element using:
validationManager.validateForm(angular.element(document.querySelector('#patientForm')));
That did the trick and fired the validation.