Last active
December 25, 2015 06:29
-
-
Save thewinterwind/6932591 to your computer and use it in GitHub Desktop.
Input and Textarea Validation in Twitter Bootstrap 3 (author: Anthony Vipond)
This file contains 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
/** | |
* Construct feedback html for blur event on inputs and textareas | |
* @param {String} icon_msg | |
* @param {String} icon_class | |
* @return {String} html | |
*/ | |
function get_feedback_html(icon_msg, icon_class) { | |
var html = | |
'<span class="alert-msg"><i class="' + icon_class + '">' + icon_msg + '</i></span>'; | |
return html; | |
} | |
/** | |
* Append or update a span based on validation result | |
* @param {Object} element | |
* @param {String} result | |
* @param {String} icon_msg | |
* @return {undefined} | |
*/ | |
function append_or_update_span(element, result, icon_msg) { | |
if ( element.next().is('span') ) { | |
var icon_class = result == 'error' ? 'icon-remove-sign' : 'icon-ok-sign'; | |
element.parent() | |
.removeClass('success error') | |
.addClass(result); | |
element.next().find('i') | |
.removeClass() | |
.addClass(icon_class) | |
.text(icon_msg); | |
} else { | |
var form_feedback = get_feedback_html(icon_msg, icon_class); | |
element.after(form_feedback); | |
} | |
} | |
// Base form validation rules | |
$('input, textarea').on('blur', function() { | |
var self = $(this); | |
// The following doesn't validate | |
if ( $.trim($(this).val()) == '' ) { | |
$(this).parent().addClass('error'); | |
var icon_msg = ' Please input a value'; | |
append_or_update_span(self, 'error', icon_msg); | |
} else { | |
// The following validates | |
$(this).parent().addClass('success'); | |
var icon_msg = ' Value accepted'; | |
append_or_update_span(self, 'success', icon_msg); | |
} | |
}).on('focus', function() { | |
$(this).removeClass('success error'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment