I\'m working on a JSF form prototype for inserting data into database table using AJAX data validation This is the JSF page:
Just add listener in your tag h:inputText
:
<h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}"
valueChangeListener="#{DatabaseController.validateSessionid}">
So you can check the entered value on the server side. When a user tabs out of the input field, JSF makes an ajax-call to the server and runs the name input component through the execute portion of the life cycle. This means that JSF will invoke the name input's value-change listener specified in attribute valueChangeListener
during the validations process phase of the life cycle.
And I would suggest to implement this method:
public void validateSessionid(ValueChangeEvent e) {
UIInput nameInput = e.getComponent()
String sessionid = nameInput.getValue()
//do SQL query
}
After the ajax-call returns JSF renders the h:outputText id="sessionidvalidate"
.
You need to create a Validator
.
Kickoff example:
@FacesValidator("sessionIdValidator")
public class SessionIdValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
// ...
if (yourDataService.existSessionId(value)) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Session ID is already in use, please choose another.", null));
}
}
}
Use it as follows:
<h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}">
<f:validateLength minimum="0" maximum="15" />
<f:validator validatorId="sessionIdValidator" />
<f:ajax event="blur" render="sessionidMessage" />
</h:inputText>
<h:message id="sessionidMessage" for="sessionid" />
Note that you should use a <h:message>
to show validation messages. You haven't any one in your view. Apply the same for all your other fields:
<h:inputText id="userid" value="#{DatabaseController.formMap['userid']}">
<f:validateLength minimum="0" maximum="15" />
<f:ajax event="blur" render="useridMessage" />
</h:inputText>
<h:message id="useridMessage" for="userid" />
If you want to use @Resource
or @EJB
or @Inject
in the validator, then replace the @FacesValidator
annotation by @ManagedBean
or (as you seem to use CDI for some reason) @Named
:
@Named
public class SessionIdValidator implements Validator {
@Resource
private DataSource dataSource;
@Inject
private YourDataService yourDataService;
// ...
}
and use it as follows instead
<f:validator binding="#{sessionIdValidator}" />