Form validation in JSF

K

kosl

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 ?

I would be grateful for any suggestions.

kind regards

karol oslowski
 
H

hiwa

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 ?

I would be grateful for any suggestions.

kind regards

karol oslowski

If you want component specific error message, you have to write
a custom validator implementing Validator interface. Also, in
order to use your validator as a tag, you have to write a tag
handler and TLD. Adding to them, you should register your
validator and its ID in the faces-config.xml file.
 
W

writeOnceDebugEverywhere()

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

KB Oslowski

writeOnceDebugEverywhere() said:
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>



- well, that's it ;-
Thank you awfully for your answer just it does not solve my problem. I managed to figure out what you are describing before just the problem is that the validators are NOT called when the field is
empty. And I want to make sure that the field will NOT be empty. Using required attribute is not an option (AFAIK) as I would like to have different validation error messages for different fields in
the form. Another option is to do this kind of validation upon submission of the form (via action event) but I don't like it very much as I'd prefer to indicate which fields are required in the .jsp
source and not in the backing bean code. Any suggestions?

k.
 
W

writeOnceDebugEverywhere()

KB said:
Thank you awfully for your answer just it does not solve my problem. I
managed to figure out what you are describing before just the problem is
that the validators are NOT called when the field is empty. And I want
to make sure that the field will NOT be empty. Using required attribute
is not an option (AFAIK) as I would like to have different validation
error messages for different fields in the form. Another option is to do
this kind of validation upon submission of the form (via action event)
but I don't like it very much as I'd prefer to indicate which fields are
required in the .jsp source and not in the backing bean code. Any
suggestions?


-Hhmm... let say about standard UIInput component / <h:inputText> tag.
Then try to extend UIInput/HtmlInputText, in order to override
validate() method, in the following way:

public void validate(FacesContext context) {
Object submittedValue = getSubmittedValue();
// check for null or empty submitted value first:
if ((submittedValue == null) ||
(submittedValue instanceof String) &&
(((String) submittedValue).length() < 1)) {
Validator[] v = getValidators();
int index = 0;
while(index < v.length) {
// go trough validators & just call your special
validator.
// Actually, we just need a custom message from
validator,
// nothing else. Because of that, this code
probably can be improved,
// in order to not use custom validator at all !!!
// By the way, your special not-null validator _always
// throws ValidateException (of course, after
loading error
// message from the bundle):

Validator validator = v[index];
if (validator instanceof MyValidator){
try {
validator.validate(context, this, null);
}
catch (ValidatorException ve) {
// If the validator throws an exception, we're
// invalid, and we need to add a message
setValid(false);
FacesMessage message = ve.getFacesMessage();
if (message != null) {
message.setSeverity(FacesMessage.SEVERITY_ERROR);
context.addMessage(getClientId(context),
message);
}
}// of try()
}
index++;
}// of while()

}// null submitted value
else{
super.validate(context);
}
}// of validate()
-------------
I think, instead of standard HtmlInputText component, you can register
this new component
(see jsf-impl.jar/standard-html-renderkit.xml or something like that)...

Hope this helps...
 
W

writeOnceDebugEverywhere()

writeOnceDebugEverywhere() said:
// in order to not use custom validator at all !!!
// By the way, your special not-null validator _always
// throws ValidateException (of course, after

-correction: custom validator yet must to check for a null value, before
throw ValidatorException; othervise super.validate() will always throw
this ex. (even for non-null value)...
 
D

Dan Hinojosa

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 ?

I would be grateful for any suggestions.

kind regards

karol oslowski

Use component binding:

<h:form>
<h:inputText validator="#{myBean.validateText}"/>
<h:eek:utputText binding="#{myBean.errorComp}"/>
<h:commandButton value="test"/>
</h:form>

package com.mycompany.beans;

import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;

public class MyBean {

private HtmlOutputText errorComp;

public void setErrorComp(HtmlOutputText errorComp) {
this.errorComp = errorComp;
}

public HtmlOutputText getErrorComp() {
return errorComp;
}

public void validateText(FacesContext context, UIComponent comp,
Object value) {

if ("".equals(value)) {
//Put your superduper custom message here
//and leverage comp and context

error.setValue("Nope sorry");
error.setStyle("color:red");
comp.getAttributes().put("style", "color:red");
} else {
errorComp.setValue(null);
errorComp.setStyle(null);
comp.getAttributes().put("style", null);
}
}
}
 
M

Marten Lehmann

Hello,
-correction: custom validator yet must to check for a null value, before
throw ValidatorException; othervise super.validate() will always throw
this ex. (even for non-null value)...

I am struggeling at the same problem. The custom validator doesn't even
get called when the field is empty! It has no possiblity to throw
anything, no matter if required="true" is set or not. Any ideas?

Regards
Marten
 
Joined
Oct 5, 2007
Messages
1
Reaction score
0
solution for same problem (skip required attribute)

Hi Karol ,
Congrats you got the solution. I am facing same problem can you please provide me the solution.
Thanks
Meraj
kosl said:
Thank you very much for the advise. It solved my problem.

kind regards

Karol Oslowski
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,125
Latest member
VinayKumar Nevatia_
Top