pythonweb2pyweb2py-modules

How to set IS_NOT_EMPTY and string (not included 0-9) in web2py data structure


I am developing web2py - Models - db_testing.py in pythonanywhere.com

below code is running successfully:

# -*- coding: utf-8 -*-
db = DAL('sqlite://storage.sqlite')
db.define_table('registration',
    Field('firstname', requires=IS_NOT_EMPTY(error_message='Should not left blank')),
    Field('lastname', requires=IS_NOT_EMPTY()),
    Field('gender', requires=IS_IN_SET(['Male', 'Female'])),
    Field('birthday', 'date'),
    Field('email', requires = IS_EMAIL(error_message='invalid email!')),
    Field('salary', 'integer'),
    Field('seniority', 'integer')
    )

However, the first field 'firstname' can only prevent form filling not to left blank. It cannot validate the input is in a-z or A-Z.

The last field 'seniority' can assure form filling must be 0-9, but it cannot prevent form filling not to left blank.

How can I set both requirements (IS_NOT_EMPTY with error_message and assure input is string / integer)?

Any thoughts?


Solution

  • As noted in the documentation, the requires attribute of a Field can be a list of validators. So, you can do something like this:

    Field('firstname', requires=[IS_NOT_EMPTY(), IS_ALPHANUMERIC()])
    

    To limit to just letters, use IS_MATCH with a regular expression:

    Field('firstname', requires=[IS_NOT_EMPTY(), IS_MATCH('^[a-zA-Z]+$')])
    

    Above, you do not necessarily need the IS_NOT_EMPTY validator, as the regular expression in IS_MATCH requires at least one letter, but you may want to keep IS_NOT_EMPTY in order to display a different error message specifically for empty responses.