问题
I am struggling with a custom validator for a text field. It seems that the custom validation only works AFTER the required validation is executed. This means that a field without a requiredValidator cannot be custom validated - is that true? What I want to do:
I have a text field. The value is only required if a specific value in another field is selected (here this is a checkbox group). It is a dependant validation. My custom validator works fine until the text field is required - but this should not be the case.
checkbox does not have the specific value -> text field can be blank
checkbox holds the value -> text field must have a value.
Any ideas?
<xp:inputText id="inputText1" disableClientSideValidation="true">
</xp:inputText>
<xp:inputText id="inputText2" disableClientSideValidation="true">
<xp:this.validators>
<xp:customValidator message="err">
<xp:this.validate><![CDATA[#{javascript:if(getComponentValue("inputText1").length>0 && getComponentValue("inputText2").length==0) postValidationError(this, "foo")}]]></xp:this.validate>
</xp:customValidator>
</xp:this.validators>
</xp:inputText>
Where getComponentValue is a method to receive either the value with getValue or getSubmittedValue from the component and postValidationError is a method to add a faces message.
EDIT & FINAL ANSWER
Conclusion and a sample here: http://mardou.dyndns.org/Privat/osnippets.nsf/id/OBUE-95BLK4
回答1:
The required validator is always the first validator which will be executed during the validation. That means that the answer to the first part of your question is YES.
But this does not mean that you need a required validator to use a custom validator: This part of your question has to be answered with a clear NO.
The required validator is a special kind of "hack", because a validator is only executed if your component receives a new value (aka not blank).
I am not sure why you have a problem with a custom validator - in the scenario you are describing you are just using a required validator...
EDIT:
Just "turn your validators around": Add the custom validator from inputText2 to inputText1 and it should work.
EDIT 2:
<xp:inputText id="inputText1" disableClientSideValidation="true">
<xp:this.validators>
<xp:customValidator message="err">
<xp:this.validate><![CDATA[#{javascript:
var val = getComponent("inputText2").getSubmittedValue();
if( val.equals("") == true )
return false;
null}]]>
</xp:this.validate>
</xp:customValidator>
</xp:this.validators>
</xp:inputText>
<xp:inputText id="inputText2" disableClientSideValidation="true" />
来源:https://stackoverflow.com/questions/15098964/customvalidator-without-requiredvalidator