0

With Angular forms, it's easy to see if a form is $valid or $invalid. This is great and I only allow a user to submit the form if it is $valid.

But, is there an easy way to indicate that it is in the process of validating? (and we're not clear if it's valid or invalid)

This is desirable if you are checking (e.g.) that an email address is valid. I don't want to mark the field as being $invalid until the AJAX call has returned (otherwise I could be showing an error to the user when there isn't one). But I don't want them to be able to submit if we're still checking the email address...

Any suggestions?

The code I'm using for my AJAX validators is based on AngularJS: integrating with server-side validation (thanks to @BenLesh).

function linkFunc(scope, el, attr, ctrl) {
  // When the scope changes, check the email.
  scope.$watch(attr.ngModel, validate);

  function validate (value)
  {
    // Show as valid until proven invalid
    ctrl.$setValidity('validateEmail', true);

    // if there was a previous attempt, stop it.
    if(timeoutId) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(function() {
      // Make $http call and $setValidity
      $http.get(url)
      .then(function(data) {
        ctrl.$setValidity('validateEmail', data.isValid);
      });
    }, 200);
  }
}

1 Answer 1

0

You can make the button disable while the ajax request is being processed. You can have a similar logic using fieldset too checkout the manual for it fieldset.

function validate (value)
{
  ctrl.waitingForAjax = true; // disable the required part while waiting for the response      // Show as valid until proven invalid
  ctrl.$setValidity('validateEmail', true);

  // if there was a previous attempt, stop it.
  if(timeoutId) {
    clearTimeout(timeoutId);
  }

  timeoutId = setTimeout(function() {
    // Make $http call and $setValidity
    $http.get(url)
    .then(function(data) {
      ctrl.$setValidity('validateEmail', data.isValid);
      ctrl.waitingForAjax = false; // you can enable your button once you got the response
    });
  }, 200);
}

Then in your view:

<button ng-disabled="waitingForAjax" ../>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - v obvious answer. I've tweaked it a bit to instead set ctrl.validating = true. Then in my view I check vm.formName.emailFieldName.validating (vm as I used controllerAs: vm).
Thanks, you can also use $http.pendingRequests to check whether there is any pending request globally. It may be handy for you in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.