Dynamically generating validation attribute on input using interpolation

天大地大妈咪最大 提交于 2021-02-10 05:24:45

问题


Edit: This question is no longer relevant as of Angular version: 1.3.0-beta.12 you can now parse ng-minlength and ng-maxlength dynamic values. See: https://github.com/angular/angular.js/issues/5319

My problem is quite simple: I need to dynamically create input validation (ex. ng-minlength) using interpolation.

And doing that I am running into some issues specifically generating the validation attributes for ng-minlength and ng-maxlength. I assume this is due to them only taking constants?

Below you can see my code, the reason I am using a wrapper through outerForm is that I cannot dynamically generate the name attribute of input elements using interpolation, and that I have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

So again, the problem lies in the attribute ng-minlength="field.ValidationAttributes['data-val-length-min']" not being properly set.

When I print the value directly using {{field.ValidationAttributes['data-val-length-min']}} the value appears correct.

Do I have to create a directive to parse my information, do I need to create my own min/max validation or am I simply running into a syntax error?

<form name="outerForm">
   <div ng-repeat="field in logEntry.StringValues">
      <ng-form name="innerForm">
         <input type="text" name="foo" ng-model="item.foo" ng-minlength="field.ValidationAttributes['data-val-length-min']" required/>
         <span ng-show="innerForm.foo.$error.required">required</span>
         <span ng-show="innerForm.foo.$error.minlength">to short</span>
      </ng-form>
   </div>
</form>

回答1:


Hi you can use double {} to interpolate dynamic validation rules please see here: http://jsbin.com/xayiro/1/

If you can post you field.ValidationAttributes model I can update jsbin.

HTML:

 <ng-form name="innerForm">
     <input type="text" name="foo" ng-model="item.foo" ng-minlength="{{validation.minlength}}" required/>
     <span ng-show="innerForm.foo.$error.required">required</span>
     <span ng-show="innerForm.foo.$error.minlength">to short</span>
  </ng-form>

JS:

 $scope.validation= {

    maxlength:20,
    minlength:3
  };


来源:https://stackoverflow.com/questions/24604893/dynamically-generating-validation-attribute-on-input-using-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!