R0b0tn1k
R0b0tn1k

Reputation: 4306

Mootools Form.Validator checkbox

I want to validate a checkbox. Actually multiple ones with one and same name:

<input type="checkbox" name="somefield" value="1">1
<input type="checkbox" name="somefield" value="2">2
<input type="checkbox" name="somefield" value="3">3

I want to make sure at least one box is checked before the form is submitted.

So i've added a validator:

Form.Validator.add('isChecked', {
    errorMsg: 'One of these fields is required',
    test: function(element){
        if (element.type == 'checkbox' || element.checked==true) return false;
        else return true;
    }
});

But that requires all fields to be checked...

In the least case i want to pop out the same Form.Validator.Tips error message (cant figure out how that is fired)...

So how do i go about dealing with this?

Upvotes: 0

Views: 1161

Answers (4)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

there is a validator provided already that is more appropriate, which you can see here:

https://github.com/mootools/mootools-more/blob/master/Source/Forms/Form.Validator.js#L503-512

['validate-one-required', {
    errorMsg: Form.Validator.getMsg.pass('oneRequired'),
    test: function(element, props){
        var p = document.id(props['validate-one-required']) || element.getParent(props['validate-one-required']);
        return p.getElements('input').some(function(el){
            if (['checkbox', 'radio'].contains(el.get('type'))) return el.get('checked');
            return el.get('value');
        });
    }
}]

Upvotes: 2

R0b0tn1k
R0b0tn1k

Reputation: 4306

Apparently there is a validator for that:

validate-required-check

Doh!

Upvotes: 2

kolin
kolin

Reputation: 2344

I would imagine something like:

function test(element){
    var anyChecked = false;
    $$('input[type=checkbox]').each(function (el) {
        if(el.checked){
            anyChecked = true;
        }
    return anyChecked;
}

probably a more efficient way of doing this.

Upvotes: 0

Related Questions