1

In html there are three files with difference only name like : number_1 , number_2, number_3. I want to do validation like above with concise of js code.But it doesn't working. Could anybody have solution about this issue ?

This is my HTML for which i want to do jquery validation with the help of below mentioned jquery rules method :

    <form id="cc_form" method="post" action="">
    <div id="container">
    <div id="block1">
    CC_number_1 : <input type="text" id="number_1" name="number_1"> <br>
    </div>
    <div id="block2">
    CC_number_2 : <input type="text" id="number_2" name="number_2"> <br>
    </div>
    <div id="block3">
    CC_number_3 : <input type="text" id="number_3" name="number_3"> <br>
    </div>
    </div>
    <input type="submit" value="submit" name="submit">
    </form>

This is my validation script through which i want to do validation like below. Jquery library files include script is not included here. So please add those files to do validation like below.

    $("#cc_form").validate({

    rules:{
    [name^='number_']:{
    required:true
    }

    },
    messages:{
    [name^='number_']:{
    required:"Enter number"
    }
    }


    });
    enter code here

In html there are three files with difference only name like : number_1 , number_2, number_3. I want to do validation like above with concise of js code.But it doesn't working. Could anybody have solution about this issue ?

Sparky
  • 98,165
  • 25
  • 199
  • 285
badal
  • 73
  • 1
  • 9

2 Answers2

2

Try this :-

$(document).ready(function(){
$("#cc_form").validate();
    $("input[id*=number]").each(function() {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "This is required field"
            }
        });
    });
  });

The .validate() documentation is a good tutorial,and how to add rules .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

Please make sure first you need load Jquery library first and after that jquery.validate.min.js

Roopendra
  • 7,674
  • 16
  • 65
  • 92
0

First of all - [name^='number'] isn't proper object label - you've got to encapsulate it with quotes. And, unfortunately it still won't work, as, apparently rules and message labels need to be id's for specific elements and not selectors.

Working fiddle here: http://jsfiddle.net/6nNRD/

eithed
  • 3,933
  • 6
  • 40
  • 60