views:

411

answers:

2

I have five forms in the page. I have my validation also in place using jquery validation plugin. There is this odd little case where I want to cover - wherein the server returns no results (for any of the forms) and I need to display the same jquery validation. I was able to do that with :

$("#form1").validate().element( ".myid" );             

Now I am stuck at the implementing this for all five forms (five forms- five fields respectively).

One way being the legacy if-else way

var re5digit=/^\d{5}$;
if (document.myform.myid.value.search(re5digit)==-1){
alert("1");
} 
(if (document.myform.myid2.value.search(re5digit)==-1){
alert("2");
}
...

OR ask you for a jquery hack that could find me the current cursor position and I could call the validate? suggestions?

+1  A: 

I'm not sure I quite understand how your page layout and validation is set up, but you may be able to store the last form that had a focused element in it:

var lastFocusedForm;
$('input').focus(function() {
  lastFocusedForm = $(this).parents('form');
});

// and then when you need to validate...
lastFocusedForm.validate().element( ".myid" );
James Kolpack
@James - this is close to what I am looking for, but what if each of the forms has different ids?
bob
Also the forms are not nested. i.e the page has many forms spread out.. so $(this).parents('form'); wouldn't work - would it?
bob
The '$(this)' in the context of the $('input').focus(function(){$(this)}) refers to the element which has been focused. So, if you search the DOM tree upwards using the parents() function for the 'form' element, it will match the form element which contains that element. It's good that the forms are not nested - nesting forms is invalid html. Also, I'm not sure that the '.element(".myid")' is needed for validation. Running '.validate()' on the form element should be sufficient.
James Kolpack
A: 

I think that you need to use a bit different approach. Each validation request should belong to the exact form. Using your way it'll be easy to create situation when validation messages for, for example, 1st form will be displayed in 2nd form. In order to avoid such bugs you should assign unique IDs to forms and use javascript closures ( http://odetocode.com/Blogs/scott/archive/2007/07/10/closure-on-javascript-closures.aspx and http://www.jibbering.com/faq/faq_notes/closures.html) in your ajax submit function.

$(document).ready(function(){ 
    var form = $("#ajax-form");
    form.submit(function(){ 
        $.post( 
            "/controller/path", 
            form.serialize(), 
            function(receivedData){ 
                alert(receivedData); 
                form.whateveryouwant(); // do whatever you want with your form
           } 
       ); 
   }); 
});  
zihotki