Created
April 19, 2012 04:21
-
-
Save mikeobrien/2418555 to your computer and use it in GitHub Desktop.
Simple validation for bootstrap horizontal forms
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
(function() { | |
var plugin = function($) { | |
$.fn.validate = function (selectors, predicate, message) { | |
if (!$.isArray(selectors)) selectors = [selectors]; | |
var controlGroups = []; | |
var values = []; | |
for (index in selectors) { | |
var input = this.find(selectors[index]); | |
if (input.length == 0) throw 'Selector invalid: ' + selectors[index]; | |
input = $(input[0]); | |
values.push(input.val()); | |
var element = input; | |
while (true) { | |
element = element.parent(); | |
if (element.hasClass('control-group') || element == null) break; | |
} | |
if (element) { | |
controlGroups.push(element); | |
element.removeClass('error'); | |
element.find('.help-inline').html(''); | |
} | |
} | |
var result = predicate.apply(this, values); | |
if (result) { | |
for (index in controlGroups) { | |
controlGroups[index].addClass('error') | |
controlGroups[index].find('.help-inline').html(message) | |
} | |
} | |
return result; | |
} | |
} | |
if (typeof define === 'function' && define.amd) { | |
define(['jquery'], plugin); | |
} else { plugin(window.jQuery) } | |
})(); |
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
class AddView extends Backbone.View | |
... | |
save: -> | |
if @$el.validate('#username', ((x) -> x == ''), 'Username cannot be blank') | | |
(@$el.validate('#password', ((x) -> x == ''), 'Password cannot be blank') || | |
@$el.validate(['#password', '#password2'], ((x, y) -> x != y), 'Passwords do not match')) then return false | |
@model.save... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment