Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a form on Click event with validator jQuery

I am using jQuery validate for validate an input. My code:

 $('#button').click( function() {       
    $("#form").validate({              
        rules: {
            phone: {
                required: true,
                number: true,
                rangelength: [7, 14]
            }
        }
    }); 
});

And the HTML:

<form id="form" name="form" method="post" action="">
 <input id="phone" name="phone" class="required" type="text" />
 <div class="button" id="send_b">Send</div>
 </form>

This code is not working. If I add this line of jQuery

$("#form").submit();  

inside the click event it works. But I don't want to submit the form so I want just to make the validation on click.

Does anyone know how to do this?

like image 774
novellino Avatar asked Sep 16 '11 13:09

novellino


People also ask

How can call validate method in button click in jQuery?

$(document). ready(function(){ $("#form1"). validate({ rules: { field1: "required" }, messages: { field1: "Please specify your name" } }) $('#btn'). click(function() { $("#form1").

How do you check whether a form is valid or not in jQuery?

$("#form_id"). valid(); Checks whether the selected form is valid or whether all selected elements are valid. validate() needs to be called on the form before checking it using this method.

How can I get TextBox required field on button click in jQuery?

Inside the document. ready event handler, the Validate Button has been assigned with a Click event handler. When the Validate Button is clicked, first the TextBox is referenced using jQuery and then its value is trimmed and compared with an Empty string.

What is validator addMethod in jQuery?

validator. addMethod( name, method [, message ] ) Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.


1 Answers

Just add .form() to manually trigger the validation immediately (the default behavior waits for a submit event):

$('#button').click( function() {       
  $("#form").validate({              
    rules: {
      phone: {
        required: true,
        number: true,
        rangelength: [7, 14]
      }
    }
  }).form(); 
});
like image 78
Jens Roland Avatar answered Sep 20 '22 17:09

Jens Roland