jqueryjquery-validatejqueryform

How to remove Jquery Validation Error Messages on click of Clear Button


Edit User and Clear User are separate buttons.

Then how will Clear the error message on click of Clear Button using following statement validator.resetForm(); ?

function clearUser(){ 
       // Need to clear previous errors here 
} 


function editUser(){     
    var validator = $("#editUserForm").validate({ 
            rules: {                             
                userName: "required" 
        },  
        errorElement: "span" ,                
        messages: { 
          userName: errorMessages.E2 
        } 
      }); 

     if(validator.form()){  
        // form submition code 

    } 
} 

Solution

  • just make it global, eg:

    var validator;
    $(document).ready(function() {
           validator = $('#editUserForm');
    });
    
    function clearUser(){ 
           validator.resetForm();
    } 
    
    function editUser(){     
        validator.validate({ 
                rules: {                             
                    userName: "required" 
            },  
            errorElement: "span" ,                
            messages: { 
              userName: errorMessages.E2 
            } 
          }); 
    
         if(validator.form()){  
            // form submition code 
        } 
    } 
    

    then you need to eliminate the var in editUser().

    btw - you can also do:

    function clearUser(){ 
           var validator = $('#editUserForm');
           validator.resetForm();
    }