JQuery addMethod validation plugin

I am trying to use the jQuery validation plugin to validate multiple form fields using custom add.method and I need help. Here is my html form.

<form method="post" action="<?=$PHP_SELF?>" name="sf" id="sf"> <p> <label for="name">Name:</label> <input type="text" name="name" id="name" /><br /> </p> <p> <label for="email">Email:</label> <input type="text" name="email" id="email" /><br /> </p> </form> 

Basically, I am trying to establish a very basic rule to check if the Name field is empty. I'm trying to follow, please let me know if this is correct?

 <script type="text/javascript"> $(document).ready(function() { $.validator.addMethod("name",function(value,element){ return this.optional(element) || (i.test(value) > 0); },"Name is required"); $("#sf").validate({ rules: { name: true, }, }); }); </script> 

I want to display a name error message before the Name field on the form. How can i do this? Thanks for any help.

+4
source share
2 answers

If you want to simply create the required form element, you must add the required class to the element:

 <input type="text" name="name" id="name" class="required" /> 

This will automatically receive confirmation.

If you are doing this just to figure out how to add a custom rule, I would recommend not using a rule called "name" (I had problems with it in a simple example). Here you can add a custom rule guaranteeing "name" only characters:

 $.validator.addMethod("customname", function(value, element) { var i = /^[A-Za-z]+$/; return this.optional(element) || (i.test(value) > 0); }, "Name is required"); $("#sf").validate({ rules: { name: { customname: true } } }); 

Note that inside the rules object you must specify another object ( name ) that defines the rules for this element.

As for placing the error in a specific place, check the errorPlacement parameter:

 errorPlacement: function(error, element) { element.closest("p").prepend(error); } 

Puts an error between the label and input .

Here is an example of two actions: http://jsfiddle.net/andrewwhitaker/7xD2H/

+6
source

This will accomplish what you are trying to do:

  $(document).ready( function() { $('#sf').validate(); $("#name").rules("add", { required: true, minlength: 0, messages: { required: "Name is required" } }); }); 
0
source

Source: https://habr.com/ru/post/1337694/


All Articles