Created
November 29, 2010 22:28
-
-
Save amiel/720765 to your computer and use it in GitHub Desktop.
very simple custom form validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var validate = (function() { | |
var c = { log: function() {} }; | |
// var c = console; | |
var f = function() { | |
$(this).each(function() { | |
var t = $(this); | |
if (validate_presence_of(t)) return; | |
if (t.attr('name').match(/email/i)) | |
if (validate_email(t)) return; | |
if (t.attr('data-confirm')) | |
if (validate_confirmation_of(t, t.parents('form').find('[name=' + t.attr('data-confirm') + ']'))) return; | |
}); | |
}; | |
f.has_errors = false; | |
var validate_presence_of = function(t) { | |
c.log('validate_presence_of', t); | |
if ($.trim(t.val()) != "") { | |
return hide_error(t); | |
} else { | |
return show_error(t, "cannot be blank"); | |
} | |
}; | |
var email_regex = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i; | |
var validate_email = function(t) { | |
c.log('validate_email', t); | |
if (email_regex.test(t.val())) { | |
return hide_error(t); | |
} else { | |
return show_error(t, "does not look like an email address"); | |
} | |
}; | |
var validate_confirmation_of = function(t, password_field) { | |
c.log('validate_confirmation_of', t, password_field); | |
if (t.val() == password_field.val()) { | |
return hide_error(t); | |
} else { | |
return show_error(t, 'must match password'); | |
} | |
}; | |
var show_error = function(t, message) { | |
c.log('show error', t, message); | |
var container = t.parents('li'), | |
inline_message = container.find('.inline_message'); | |
f.has_errors = true; | |
if (inline_message.length == 0) { | |
inline_message = $('<span>').addClass('inline_message'); | |
container.append(inline_message); | |
} | |
container.addClass('error'); | |
inline_message.text(message).show(); | |
return true; | |
}; | |
var hide_error = function(t) { | |
c.log('hide error', t); | |
var container = t.parents('li'), | |
inline_message = container.find('.inline_message'); | |
container.removeClass('error'); | |
inline_message.hide(); | |
return false; | |
}; | |
return f; | |
})(); | |
var validateable_inputs = 'input[type=text],input[type=password]'; | |
$('form').submit(function() { | |
validate.has_errors = false; | |
validate.apply($(validateable_inputs, this)); | |
return !validate.has_errors; | |
}).find(validateable_inputs).blur(validate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment