Form Validation with Dependent Fields in AngularJS

前端 未结 2 664
执念已碎
执念已碎 2021-01-12 16:54

I have an object that has 2 fields, while 1 should be less than or equal to another.

Say it\'s HDD quota settings and I need the threshold to be less th

2条回答
  •  轮回少年
    2021-01-12 17:18

    I have played with custom directives and cooked something that works for my case.

    On my input for threshold I have less-than-or-equal="quota.size" directive, passing it the model's property to validate against (I want quota.threshold to be less than or equal to quota.size):

    
    

    In link function of lessThanOrEqual directive it starts to watch the quota.size and when quota.size changes it just tries to set the current view value of threshold on model:

    link: (scope, elem, attr, ctrl) ->
        scope.$watch attr.lessThanOrEqual, (newValue) ->
            ctrl.$setViewValue(ctrl.$viewValue)
    

    Then there is the parser that does the validation by calling scope.thresholdValidate(thresholdValue) method passing it the candidate value. This method returns true if validation succeeded and if it does - it returns the new value, otherwise - current model's value:

        ctrl.$parsers.push (viewValue) ->
            newValue = ctrl.$modelValue
            if not scope.thresholdValidate viewValue    
                ctrl.$setValidity('lessThanOrEqual', false)
            else
                ctrl.$setValidity('lessThanOrEqual', true)
                newValue = viewValue
            newValue
    

    I am pushing the parser to parser collection, as opposite to unshifting it like most of the examples suggest, because I want angular to validate required and number directives, so I get here only if I have a valid and parsed number (less work for me, but for text inputs I probably should do the parsing job)

    Here is my playground: http://embed.plnkr.co/EysaRdu2vuuyXAXJcJmE/preview

提交回复
热议问题