问题
I have been trying to do client validation using jQuery validation plugin with a form built with jsf.I need client validation basically to help reduce the number of request/response round trips between server and browsers for obvious reasons. i know that jsf "h:commandlink" tag is not like a regular submit button,like the "h:commandButton" which i have gotten to work successfully with JQuery form validation with the code below:
<script type = "text/javascript">
$(document).ready(function(){
$("#form").validate({
rules: {
"form:staffno": {
required: true
}
}
});
});
</script>
<h:body>
<h:form id="form">
<h:inputText id="staffno" value="#" required="true"/>
<h:commandButton id="save" value="SAVE" action="#"/> //renders a html submit button type
</h:form>
</body>
I noticed from the page source that h:commandLink uses some kind of javascript function, so i tried to tweak the above to get the same effect as shown below:
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
rules: {
"form:staffno": {
required: true
}
}
});
$("#form\\:save").click(function(){
if($("#form").valid()){
//cannot use regular $("#form").submitt()
// really can't figure what to use here
}
else{
return false;
}
});
});
</script>
In my tweaking spree, i was able to get the JQuery validation plugin behaviour,but only for a short while , because the form still gets submitted, even if the field is empty. I kind of like figured that two onclicks are called, one, in jquery and another in jsf.I still can't figure how to get it right. I will need help to get this client validation working correctly with JQuery and jsf h:commandLink. Thanks
回答1:
Just return true if the form is valid. You can even just delegate straight to valid() function.
$("#form\\:save").click(function(){
return $("#form").valid();
});
You can indeed not use $("#form").submit(), because this way the name=value pair of the HTML <input type="submit"> representation of the command button won't be sent as a request parameter and hence JSF won't be able to identify the command button action which needs to be invoked.
回答2:
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
rules: {
"form:staffno": {
required: true
}
}
});
$("#form\\:save").click(function(){
return $("#form").valid();
});
</script>
<body>
<h:form id="form">
<h:inputText id="staffno" value="#" required="true"/>
<!-- renders a html submit button type -->
<h:commandButton id="save" value="SAVE" action="#"/>
</h:form>
</body>
script not work properly when i use it in .xhtml file ................................................................................ If tags have a "type" attribute, it should equal "text/javascript" or "application/javascript". Also scripts must be parsable (syntactically correct).
来源:https://stackoverflow.com/questions/12298386/need-to-integrate-jquery-validation-plugin-with-jsf