0

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>
Lloople
  • 1,827
  • 1
  • 17
  • 31
  • Ok what's the problem?? What is your question or error you get? – Mehrdad Kamelzadeh Jun 08 '15 at 09:36
  • 1
    use `ng-required` and other `ng-` attributes for validation... Also it maybe better to have an angular function handle the submit of the form and use `$window.location` to change the page – Callum Linington Jun 08 '15 at 09:36
  • @MehrdadKamelzadeh the problem is that the form is always send. What I want is only send the form to the action url if the alias field is filled – Lloople Jun 08 '15 at 09:46
  • Please show its `controller` code as well. I think you need to call the function you want to do the work for you like this: `ng-submit="form.$valid && functionToDoTheWork()` – Mehrdad Kamelzadeh Jun 08 '15 at 09:53

1 Answers1

0

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

ababashka
  • 2,101
  • 1
  • 14
  • 15