kosl said:
Hi,
I have a problem with form validating using JSF.
As we know the validator is not called when the validated field is
empty. I know we can change it by seting the tag "required" but - then
the error message is standard and same for all validated fields. I know
how to change to message but I'm wondering whether I could have
different error messages for different fields ?
- yes, you can. As first, yu must register custom message bundle file in
the faces-config.xml, for example:
<application>
<message-bundle>custMessages</message-bundle>
<locale-config>
<default-locale>sr_YU</default-locale>
<supported-locale>en</supported-locale>
<supported-locale>sv</supported-locale>
</locale-config>
</application>
- Second, you must write a custom validator which extends
javax.faces.validator.Validator; custom JSF tag for that validator,
which extends javax.faces.webapp.ValidatorTag, and register them in the
faces-config.xml/.tld:
public class MyValidator implements Validator, Serializable{
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
Application application = context.getApplication();
// then load bundle file with your custom messages:
String messageBundleName = application.getMessageBundle();
ResourceBundle rb =
ResourceBundle.getBundle(messageBundleName, locale);
//validate whatever you want:
if (notOk()){
// finaly, get custom error message here:
String msg = rb.getString("invalid_name");
FacesMessage facesMsg =
new FacesMessage(FacesMessage.SEVERITY_FATAL, msg, msg);
throw new ValidatorException(facesMsg);
}
}// of validate()
}// of MyValidator class
<!-- register MyValidator / faces-config.xml/ -->
<validator>
<validator-id>
MY_VALIDATOR
</validator-id>
<validator-class>
MyValidator
</validator-class>
</validator>
public class MyValidatorTag extends ValidatorTag {
..........
protected Validator createValidator() {
Application application =
FacesContext.getCurrentInstance().getApplication();
MyValidator validator = (MyValidator)
application.createValidator("MY_VALIDATOR");
return validator;
}
}// of MyValidatorTag
<!-- validator tag description / .tld file: -->
<tag>
<name>validateLater</name>
<tag-class>MyValidatorTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>than</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
I would be grateful for any suggestions.
- well, that's it ;-