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 ?

2
  • This answer should help: stackoverflow.com/a/2780559/551093 Commented Feb 7, 2013 at 12:57
  • Please check my updated answer. It is working fine for me. I hope it will help you Commented Feb 7, 2013 at 14:19

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.