简体   繁体   中英

Formly input field validation

I am having an issue with validation messages appearing in an application. Here is the application demo:

https://jsfiddle.net/MrPolywhirl/yxrh3ujp/

I have tried adding validation configuration. This is straight out of the docs .

app.run(function(formlyValidationMessages) {
  formlyValidationMessages.messages.required = 'to.label + " is required"';
  formlyValidationMessages.messages.max = '"The max value allowed is " + to.max';
  formlyValidationMessages.messages.min = '"The min value allowed is " + to.min';

  formlyValidationMessages.addTemplateOptionValueMessage('pattern', 'patternValidationMessage', '', '', 'Invalid Input');
});

I have set min/max values on my field. The field does get validated correctly, but the message still does not appear.

Neither the pattern / patternValidationMessage nor the validation (config) function are working for the field. They do nothing and even with a valid pattern, the field still shows that it is invalid (highlighted red).

{
  key: 'cooldown',
  type: 'input',
  templateOptions: {
    type: 'number',
    label: 'Cooldown (in seconds)',
    min : 0,
    max : 600,
    required: true,
    //pattern: /^[0-9]+$/,
    //patternValidationMessage: '"Needs to match " + options.templateOptions.pattern'
  },
  defaultValue: 30,
  //validation: {
  //  messages: {
  //    required: function ($viewValue, $modelValue, scope) {
  //      return scope.to.label + ' is required';
  //    }
  //  }
  //},
}

Can I get some pointers as to why the message will not appear?

Carefully look at the way how formcontrol condition should be setup in error template( specially in ng-if part).

<script type="text/ng-template" id="error-messages.html">
      <formly-transclude></formly-transclude>
      <div ng-messages="fc.$error" ng-if="options.formControl.$invalid && options.formControl.$touched" class="error-messages">
        <div ng-message="{{ ::name }}" ng-repeat="(name, message) in ::options.validation.messages" class="message">{{ message(fc.$viewValue, fc.$modelValue, this)}}</div>
      </div>
</script>

Also the way you have written setWrapper method in app config looks messy, so I have removed the code to a separate template and pointed the template here.

Take a look at updated jsfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM