views:

89

answers:

2

i have to validate listbox for maximum of three items to select by the user...

i have write code that works fine...

but if i'll use the same code in customer validator in asp.net it...pop ups the msg that please select maximum of three items..but after it, the page get post back to server...that should not happen...

give me solution please on customer validator....

my code is here...for custom validator....

here lbohobby is the listbox with hobbies....

the function Validate is as follows....

function Validate() 
 { 
     var lblCount=0; 
     var lbGenre = document.getElementById("<%=lbohobby.ClientID %>");
     for(var x = 0; x < lbGenre.options.length; x++) 
     { 
          if(lbGenre.options[x].selected) 
          { 
               lblCount+=1; 
               alert(lblCount);
          } 
     } 
     if(lblCount > 3) 
     {               
          alert("maximum Three!");   
          return false; 
     } 
}

please reply me...

+1  A: 

Instead of return false you must use args.IsValid = false. You must also add the function input parameters - sender and args.

function Validate(sender, args)  
{
    args.IsValid = true
    var lblCount=0;      
    var lbGenre = document.getElementById("<%=lbohobby.ClientID %>");     
    for(var x = 0; x < lbGenre.options.length; x++)      
    {           
        if(lbGenre.options[x].selected)           
        {                
            lblCount+=1;                
            alert(lblCount);  
        }      
    }      
    if(lblCount > 3)      
    {                         
        alert("maximum Three!");
        args.IsValid = false;    
    }
}
Phaedrus
k, I have seen about 4 or 5 questions like this today ALONE, what is wrong with the ASP clientside validation! Seriously!
Zoidberg
+1  A: 

Modify your function like so:

function Validate(sender, args) 
 { 
     args.IsValid = true;
     var lblCount=0; 
     var lbGenre = document.getElementById("<%=lbohobby.ClientID %>");
     for(var x = 0; x < lbGenre.options.length; x++) 
     { 
          if(lbGenre.options[x].selected) 
          { 
               lblCount+=1; 
               alert(lblCount);
          } 
     } 
     if(lblCount > 3) 
     {               
          alert("maximum Three!");   
          args.IsValid = false;
     } 
}
zincorp