Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web2py Custom Validators

I am new to Web2py and am trying to use a custom validator.

class IS_NOT_EMPTY_IF_OTHER(Validator):

    def __init__(self, other,
                 error_message='must be filled because other value '
                               'is present'):
        self.other = other
        self.error_message = error_message

    def __call__(self, value):
        if isinstance(self.other, (list, tuple)):
            others = self.other
        else:
            others = [self.other]

        has_other = False
        for other in others:
            other, empty = is_empty(other)
            if not empty:
                has_other = True
                break
        value, empty = is_empty(value)
        if empty and has_other:
            return (value, T(self.error_message))
        else:
            return (value, None)

I do not understand how to use it on my table:

db.define_table('numbers',

    Field('a', 'integer'),
    Field('b', 'boolean'),
    Field('c', 'integer')

I want to use this in a way that 'c' cannot be left black when 'b' is ticked.

like image 211
Rahul Bhatia Avatar asked Jan 15 '23 07:01

Rahul Bhatia


1 Answers

save the code on /modules/customvalidators.py

from gluon.validators import is_empty
from gluon.validators import Validator


class IS_NOT_EMPTY_IF_OTHER(Validator):

    def __init__(self, other,
                 error_message='must be filled because other value '
                               'is present'):
        self.other = other
        self.error_message = error_message

    def __call__(self, value):
        if isinstance(self.other, (list, tuple)):
            others = self.other
        else:
            others = [self.other]

        has_other = False
        for other in others:
            other, empty = is_empty(other)
            if not empty:
                has_other = True
                break
        value, empty = is_empty(value)
        if empty and has_other:
            return (value, T(self.error_message))
        else:
            return (value, None)

then in models/db.py

from customvalidator import IS_NOT_EMPTY_IF_OTHER

db.define_table("foo",
    Field('a', 'integer'),
    Field('b', 'boolean'),
    Field('c', 'integer')
)

# apply the validator
db.foo.c.requires = IS_NOT_EMPTY_IF_OTHER(request.vars.b)

Also, note that it can be done easily without the above validator. Forget all the code above and try this simplified way

Version 2:

controllers/default.py

def check(form):
    if form.vars.b and not form.vars.c:
        form.errors.c = "If the b is checked, c must be filled"

def action():
    form = SQLFORM(db.foo)
    if form.process(onvalidation=check).accepted:
        response.flash = "success"
    return dict(form=form)
like image 126
Bruno Rocha - rochacbruno Avatar answered Jan 22 '23 16:01

Bruno Rocha - rochacbruno