Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Input and Textarea Validation in Twitter Bootstrap 3 (author: Anthony Vipond)
/**
* 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