Search code examples
javascripthtmlangularjsvalidationangular-formly

angular-formly validation message with dynamic values


I am using angular-formly and is trying to create a validation that will check if the value from the user is between two numbers that will be dynamic set, so it dose not need to be the same all the time. I thouth the easyes way to do this was with a few variables and the validation works but the message skips the variables when the error accrues.

JS Bin of my problem here

This is my validation method code:

//Default values can be changed durign runtime
var rangeMin = 0;
var rangeMax = 100;
var value;

vm.fields = [
  {
    key: 'number',
    type: 'input',
    validators: {
      ipAddress: {
        expression: function(viewValue, modelValue) {
          value = modelValue || viewValue;
          var returning = false;
          if(value > rangeMin &&  value < rangeMax)
          {
            returning = true;
          }
          return returning;
        },
        message: '$viewValue + " not in range of " + rangeMin + " and " + rangeMax'
      }
    },
    templateOptions: {
      label: 'Number',
      type: 'text',
    }
  }];

Solution

  • The issue you were having was in the message property. It's a bit confusing with the way angular treats the message, but basically the value of the message needs to be an expression the way you'd see it in an angular template. As it was your message property evaluated to:

    $viewValue + " not in range of " + rangeMin + " and " + rangeMax
    

    And that's what angular was given. So angular was able to evaluate $viewValue properly because that's in the field's $scope, however rangeMin and rangeMax are not in the field's $scope, so those evaluated to empty strings.

    So the solution is to reference the rangeMin and rangeMax directly so what you pass to angular doesn't have to evaluate those.

    $viewValue + " not in range of 0 and 100"
    

    To do this, your message property should be:

    message: '$viewValue + " not in range of ' + rangeMin + ' and ' + rangeMax + '"'
    

    Here's a working example: https://jsbin.com/fupata/edit


    Note, you can alternatively provide the rangeMin and rangeMax as data properties in your field options like so: https://jsbin.com/baxise/edit?html,js,console,output

    This makes it possible to make things a lot more reusable by allowing you to create a custom type to hold all this validation logic like so: https://jsbin.com/teleko/edit?html,js,output

    That last one is how I'd do it :-) Good luck 😀 👍