0

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?

2 Answers2

1

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.

Anthony
  • 25,466
  • 3
  • 28
  • 57
  • IS_ALPHANUMERIC() include a-z, A-Z and 0-9. Is it possible to exclude 0-9? – lawrencema Ma Apr 03 '21 at 04:30
  • 1
    See updated answer. All of the validators are documented in the book: http://web2py.com/books/default/chapter/29/07/forms-and-validators#Validators – Anthony Apr 03 '21 at 14:11
0

To check whether it's a string: if isinstance(firstname, str)

To check whether non-empty: you can do if firstname != '' or if firstname; in Python, empty objects are treated as being "False" when used as a boolean. To check whether it's letter characters, you can do if firstname.isalpha().

Acccumulation
  • 3,491
  • 1
  • 8
  • 12