John Livermore
John Livermore

Reputation: 31343

Simple jQuery validation plugin issue

I am having trouble getting a simple jQuery validation example to work. How would this fiddle be modified to make the fields validate when they lose focus?

http://jsfiddle.net/jeljeljel/wyB3w/2/

HTML

<div id="pseudoForm">
    <input type="text" name="first_name" />
    <input type="text" name="last_name" />
</div>

JS

$("#pseudoForm").validate({
    onfocusout: true,
    rules: {
        first_name: "required",
        last_name: "required"
    }
});

Upvotes: 1

Views: 957

Answers (3)

Ejaz
Ejaz

Reputation: 8872

There seem to be many things wrong with your script+markup,

  1. The input elements have got to be inside a form.
  2. The input elements got to have an id to work with your code (it has been brought to my attention, by respected fellow; Sparky, that this is not a requirement)
  3. as mentioned already, you're missing a }
  4. jQuery validate works on forms
  5. onfocusout can either be false or a function(){}

check this jsfiddle, contains corrected code

Correct HTML IMO

<form id="pseudoForm" >
    <input type="text" name="first_name" id="first_name" />
    <input type="text" name="last_name" id="last_name" />
</form>

Correct Javascript

$("#pseudoForm").validate({
    onfocusout: function(fld){$(fld).valid()},
    rules: {
        first_name: 'required',
        last_name: 'required'
    }
});

Then you've got to find some way of posting form with a mouse :D but that isn't necessary for validate to work

Upvotes: 3

Sparky
Sparky

Reputation: 98748

Since your latest edits, I only see three issues:

1) onfocusout can only be false or a function. Setting it to true will break the plugin. By default the plugin's onfocusout validation is only activated after the initial submit. So I simply modified the default callback function so that it validates immediately.

2) You can only use this plugin on form elements.

3) Enclose .validate() within a DOM ready handler.

Working DEMO: http://jsfiddle.net/cKeeN/

jQuery:

$(document).ready(function () {

    $("#pseudoForm").validate({
        onfocusout: function (element, event) {
            this.element(element);
        },
        rules: {
            first_name: "required",
            last_name: "required"
        }
    });

});

HTML:

<form id="pseudoForm">
    <input type="text" name="first_name" />
    <input type="text" name="last_name" />
</form>

Upvotes: 1

nathangiesbrecht
nathangiesbrecht

Reputation: 950

You're missing a closing } for the rules object.

Upvotes: 1

Related Questions