Javascript 如何控制角度验证器的求值顺序?

Javascript 如何控制角度验证器的求值顺序?,javascript,angularjs,typescript,Javascript,Angularjs,Typescript,使用角度1.5 我知道,当指令被激发时,角度验证器被添加到字段中,然后当控件的值改变时,所有验证器都被激发。我对金额字段有3种不同的验证(正确的字符、最大长度和不能为零)。如果字段不是有效金额,则我不需要对“不能为零”进行求值,但我想再次检查控件。$validator.amountFormat. 无论如何,是否可以保证我构建的格式验证器将出现在大于零的验证器之前。我还有很多其他的场景 这就是我所拥有的: ctrl.$validators.amountFormat = (modelValue: s

使用角度1.5

我知道,当指令被激发时,角度验证器被添加到字段中,然后当控件的值改变时,所有验证器都被激发。我对金额字段有3种不同的验证(正确的字符、最大长度和不能为零)。如果字段不是有效金额,则我不需要对“不能为零”进行求值,但我想再次检查
控件。$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;
}

下面的链接解释了$validator在$parser成功完成后启动。在
满足$validators管道的要求
部分:

因此,不要试图让验证器在彼此之前启动。我能够编写一个解析器(用简单的术语)来表示,如果用户输入了有效的数量,请将其存储在modelValue中,否则将modelValue留空

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

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

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

    return modelReturnValue;
});
然后在我的验证器中,我可以使用modelValue而不是viewValue

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;
}