2

I've got these two approaches, and they work, sort of...

The problem is that in the first case, only the first input item with that class name works.

    $.validator.addClassRules("NameField",{
        required: true,
            minlength: 2,
        uniqueName: {
          product: function() {
              return $(this).val();
          }
        },
        messages: {
           required: "Required Field",
           minlength: "Minimum 2 characters",
           uniqueName: "Name exists already",
           remote: ''
        }
    });

the problem with the second example is that the validation works, but the messages don't for the remote validator

    $(".NameField").rules("add", {
        required: true,
            minlength: 2,
        uniqueName: {
          product: function() {
              return $(this).val();
          }
        },
        messages: {
           required: "Required Field",
           minlength: "Minimum 2 characters",
           uniqueName: "Name exists already",
           remote: ''
        }

    });

and this is the code for the validator

    $.validator.addMethod("unique", function(value, element, params) {
      return $.validator.methods.remote.call(this, value, element, {
          url: 'mypage',
          data: {
              : value
          }
      });
    });

any ides?

Daniel
  • 34,125
  • 17
  • 102
  • 150

1 Answers1

4

You can not add a validation method inline as you have done with uniqueName. You must first define add the method to the validator, then you can add this in your rules.

HTML

<form class="testForm" action="" method="post">
    <input type="text" name="input1" class="NameField" />
    <input type="text" name="input2" class="NameField" />
    <input type="text" name="input3" class="NameField" />
    <input type="text" name="input4" class="NameField" />
    <input type="submit" />
</form>​

Javascript

$.validator.addMethod("uniqueName", function(value, element) {
    var parentForm = $(element).closest('form');
    if ($(parentForm.find('.NameField[value=' + value + ']')).size() > 1) {
        return false;
    }
    else {
        return true;
    }
}, "Name exists already");

$.validator.addClassRules({
    NameField: {
        required: true,
        minlength: 2,
        uniqueName: true
    }
});

$(".testForm").validate();​

Demo

Also note, you cannot add messages in the addClassRules function.

3dgoo
  • 15,716
  • 6
  • 46
  • 58