﻿$(document).ready(function() {
    // Initialize validation on the entire ASP.NET form.
    $("#aspnetForm").validate({
        // This prevents validation from running on every
        //  form submission by default.
        onsubmit: false
    });

    // Search for controls marked with the causesValidation flag 
    //  that are contained anywhere within elements marked as 
    //  validationGroups, and wire their click event up.
    $('.validationGroup .causesValidation').click(ValidateAndSubmit);

    // Select any input[type=text] elements within a validation group
    //  and attach keydown handlers to all of them.
    $('.validationGroup :text').keydown(function(evt) {
        // Only execute validation if the key pressed was enter.
        if (evt.keyCode == 13) {
            ValidateAndSubmit(evt);
        }
    });
});

function ValidateAndSubmit(evt) {
    // Ascend from the button that triggered this click event 
    //  until we find a container element flagged with 
    //  .validationGroup and store a reference to that element.
    var $group = $(evt.currentTarget).parents('.validationGroup');

    var isValid = true;

    // Descending from that .validationGroup element, find any input
    //  elements within it, iterate over them, and run validation on 
    //  each of them.
    $group.find(':input').each(function(i, item) {
        if (!$(item).valid())
            isValid = false;
    });

    // If any fields failed validation, prevent the button's click 
    //  event from triggering form submission.
    if (!isValid)
        evt.preventDefault();
}
