Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

selectBooleanCheckbox required=true not working - need custom validator?

843842Feb 7 2006 — edited Feb 8 2006
To All:

Searched the web (and this forum) and saw only one post related to this issue and it concluded that a custom validator was necessary.

I want to have the required attribute make the selectBooleanCheckbox actually required when the form is submitted.

1. Is it true that I have to wrtie a custom validator? It seems by now MyFaces or somewhere out there a validator must exist

OR

2. Does someone know how to make a checkbox required in JSF?

Many Thanks!

Matt

Comments

843842
The problem with a selectBooleanCheckbox is that it will ALWAYS return a value. Thus, if you set it to required, it doesn't matter if it's checked or unchecked, it has returned a value. It would incorrect to assume that setting the required flag to true would mean the checkbox must be checked. What if it's required to be unchecked?

Anyways, the bottom line is that you will have to create a custom validator to ensure that the checkbox is checked (or unchecked, depending on what your requirements might be). However, this is simpler than you might be thinking. Use the validator attribute and a method in your backing bean to perform the check.

Like this:
<h:selectBooleanCheckbox id="myRequiredCheckbox" 
		value="#{backBean.requiredBox}" validator="#{backBean.checked}" />
backBean will have something like the following validator method (this one throws an error if the box isn't checked):
	public void checked(FacesContext context, UIComponent component, 
		Object value) throws ValidatorException {
		
		if (context == null || component == null || value == null) 
			throw new NullPointerException();
		
		Boolean isChecked = (Boolean)value;
		
		if (!isChecked .booleanValue()) {
			FacesMessage msg = new FacesMessage("You must check the box before proceeding.");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
		}
		
	}
See, pretty easy eh?


CowKing
843842
Thanks for the help CowKing!
1 - 2
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Mar 8 2006
Added on Feb 7 2006
2 comments
89 views