﻿/*
* Copyright (c) - 2010 Luiz Thomaz
* 
* This is a very simple form validation plugin.
* To use call the validate initializer by the form element got by jquery selector
* This plugin will validate all input elements that have some special css class 
*
*/

/*
* Version: 1.0.0
* Release: 2010-01-11
*/

(function($) {
    $.fn.extend({

        validate: function() {
            $(this).bind("submit", function() {
                return $(this).isValid();
            });
        },

        isValid: function() {

            function required(el) {

                var value = $(el).is("select") ? $(el).find("option:selected").val() : $(el).val();
                if (value == '') {
                    alert("O campo " + $(el).attr("title") + " deve ser preenchido");
                    $(el).focus();
                    hasErrors = true;
                    return false;
                }
            }

            function email(el) {
                var emailRegex = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!emailRegex.test($(el).val())) {
                    alert("O campo " + $(el).attr("title") + " deve ser um email válido");
                    $(el).focus();
                    hasErrors = true;
                    return false;
                }
            }

            function money(el) {
                var numberRegex = /^((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d{2})$/;
                if (!numberRegex.test($(el).val())) {
                    alert("O campo " + $(el).attr("title") + " deve ser um valor válido");
                    $(el).focus();
                    hasErrors = true;
                    return false;
                }
            }

            var hasErrors = false;
            $(this).find(".required").each(function() { return required(this); });
            if (hasErrors) return false;

            $(this).find(".email").each(function(el) { return email(this); });
            if (hasErrors) return false;

            $(this).find(".money").each(function(el) { return money(this); });
            if (hasErrors) return false;

            return true;

        }
    });
})(jQuery);
