2017-02-15 67 views
2

使用角1.5如何控制Angular验证程序的评估顺序?

我明白,当指令被触发时角度验证器会被添加到字段中,然后当控件的值改变所有验证器的激活时。我有一个金额字段的3个不同的验证(正确的字符,最大长度,并且不能为零)。如果该字段不是有效金额,则我不需要评估不能为零,而是需要再次检查所有有效金额检查,而不是通过所有有效金额检查control.$validator.amountFormat.

有没有办法保证我构建的格式验证器将在大于零的验证器之前发生。除此之外,我还有许多其他场景。

这是我有:

ctrl.$validators.amountFormat = (modelValue: string, viewValue: string) => { 
    if (ctrl.$isEmpty(viewValue)) { 
     return true; 
    } 

    return isAmount(viewValue); 
} 

ctrl.$validators.amountGreaterThanZero = (modelValue: string, viewValue: string) => { 
    if (!isAmount(viewValue)) { //isAmount() is the function used to determine format 
     return true; 
    } 

    return parseFloat(viewValue) > 0; 
} 

这是想什么,我有:

ctrl.$validators.amountGreaterThanZero = (modelValue: string, viewValue: string) => { 
    if (ctrl.$error.amountFormat) { 
     return true; 
    } 

    return parseFloat(viewValue) > 0; 
} 

回答

2

下面的链接解释$验证火灾$解析器后成功完成。在Meet the $validators pipeline部分:

https://blog.thoughtram.io/angularjs/2015/01/11/exploring-angular-1.3-validators-pipeline.html

因此,而不是试图让验证彼此之前进行发射。我能够编写一个解析器(用简单的术语说)如果用户输入一个有效量,将其存储在modelValue中,否则将modelValue留空。

ctrl.$parsers.push((viewValue: string) => { 
    var modelReturnValue = ''; 

    if (ctrl.$isEmpty(viewValue)) { return modelReturnValue; } 

    if (this.isAmount(viewValue)) { 
     modelReturnValue = viewValue; 
    } 

    return modelReturnValue; 
}); 

然后在我的验证,而不是使用viewValue我可以使用modelValue

ctrl.$validators.amountFormat = (modelValue: string, viewValue: string) => { 
    if (ctrl.$isEmpty(viewValue)) { 
     return true; 
    } 

    //format validator still has to check the viewValue because if the user doesnt type anything in we do not want to show a format error 
    return isAmount(viewValue); 
} 

可选的,amountFormat验证可以简单地检查是否viewValue != modelValue因为如果viewValue是我们只是把它作为一个有效的金额modelValue。

ctrl.$validators.amountGreaterThanZero = (modelValue: string) => { 
    //Because we are returning an empty string if the value is not a valid amount, we can comfortably say that the modelValue will be empty 
    if (ctrl.$isEmpty(modelValue)) { 
     return true; 
    } 

    return parseFloat(modelValue) > 0; 
}