Angular validate external form before sending

555 Views Asked by At

I'm trying to validate a form before submitting to a external URL:

<form name="form" novalidate ng-submit="form.$valid && alias != ''" method="POST" action="https://sis-t.redsys.es:25443/sis/realizarPago">
    <input name="alias" ng-change="updateData(alias)" ng-model="alias" type="text" class="form-control validate" placeholder="{{ translates.alias_desc }}" required>
</form>
1

There are 1 best solutions below

0
On

You can write your own directive which will prevent default behavior of submitting form. You can do it like this:

app.directive('formValidate', ['$timeout', function ($timeout) {
  return {
    restrict: 'A',
    scope: false,
    require: 'form',
    link: function (scope, elem, attrs, formCtrl) {
      elem.on('submit', function (event) {
        if (!formCtrl.$valid) {
          $timeout(function () {
            formCtrl.$setDirty();
            formCtrl.$setSubmitted();
          });
          event.preventDefault();
        }
      })
    }
  }
}])

Note, $timeout wrapper is necessary to force call $digest and set $dirty and $submitted states to form (if you use classes ng-dirty and ng-submitted for form validation).

After you could use this directive like this:

<form name="form" novalidate form-validate method="POST" action="https://sis-t.redsys.es:25443/sis/realizarPago">
      <input name="alias" ng-change="updateData(alias)" ng-model="alias" type="text" class="form-control validate" placeholder="{{ translates.alias_desc }}" required>
      <button type="submit">Submit</button>
</form>

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