angular-formly triggering remote errors

1.6k views Asked by At

How can I trigger error on filed ? Assume we got form consist of name, email, password. We check email uniqness on server side, and server sends object like { email: ['already taken', 'another error' ] etc. How can i tap into the form and trigger those on fields?

2

There are 2 answers

2
Michael On

Sounds to me like you want to do a async validation of an input field. I assume you wanna make something like this.

For the concrete solution see this Blog

7
Michael On

I see - wasn't aware angular-formly..

you can call your validaton service in thre formly asyncValidator and then parse the result and manually set the validation state on the field using scope.fc.$setValidity. The messages can be registered in the validation section.

    validators: {
      asyncMultiValidator: {
        expression: function(viewValue, modelValue, scope) {
          $http.get('...validation-url...').success(function(result) {
            //assuming the service returns a map of validation results as {'validationName': isValid (boolean) }
            angular.foreach(result, function(isValid, validationName) {
              scope.fc.$setValidity(validationName, isValid);
            });
          })

          // this dummy validator is always valid
          return true;
        },
        message: 'dummy message - not being used'
      }
    },
    validation: {
      messages: {
        required: function(viewValue, modelValue, scope) {
          return scope.to.label + ' is required'
        },
        remote: function(viewValue, modelValue, scope) {
          return 'some remote error';
        }
      }