Skip to content

Commit

Permalink
fixes #33 - adds presence validation support for radio btns
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesmk committed May 16, 2015
1 parent c3e079e commit d97a874
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
7 changes: 6 additions & 1 deletion app/assets/javascripts/judge.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,12 @@
judge.eachValidators = {
// ActiveModel::Validations::PresenceValidator
presence: function(options, messages) {
return closed(this.value.length ? [] : [messages.blank]);
if (this.type === 'radio') {
var is_selected = root.document.querySelectorAll('[name="'+this.name+'"]:checked').length;
return closed(is_selected ? [] : [messages.blank]);
} else {
return closed(this.value.length ? [] : [messages.blank]);
}
},

// ActiveModel::Validations::LengthValidator
Expand Down
19 changes: 19 additions & 0 deletions spec/javascripts/judge-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,25 @@ describe('judge', function() {
el.value = 'foo';
expect(validator({}, { blank: 'Must not be blank' })).toBeValid();
});
it('returns invalid Validation if radio has no selection', function() {
el.type = 'radio'
el.name = 'radio_group'
el.value = 'option1'
// eachValidators.presence for radio btns rely on querySelectorAll
// so we have to add the el to the body
document.body.appendChild(el);
expect(validator({}, { blank: 'Must not be blank' })).toBeInvalid();
});
it('returns valid Validation if radio has selection', function() {
el.type = 'radio'
el.name = 'radio_group'
el.value = 'option1'
el.checked = true;
// eachValidators.presence for radio btns rely on querySelectorAll
// so we have to add the el to the body
document.body.appendChild(el);
expect(validator({}, { blank: 'Must not be blank' })).toBeValid();
});
});

describe('length', function() {
Expand Down

0 comments on commit d97a874

Please sign in to comment.