Next / Previous / Contents / TCC Help System / NM Tech homepage

54. yearCheck(): Validate a year number form entry

A utility routine to check whether a form element is a valid number, and set it to a default value if it is missing.

cbchistlib.py
# - - -   y e a r C h e c k

def yearCheck(form, eltName, desc, default):
    '''Validate or assign a default value to a form element.

      [ (form is a cgi.FieldStorage instance) and
        (eltName is the name of a form element) and
        (desc is a textual description of that element) and
        (default is its default value) ->
          if eltName is not in form ->
            return default
          else if eltName is in the form and a valid int ->
            return that int in year-number format
          else -> raise ScriptError ]
    '''

Years are always formatted in year-number format; see Section 14.4, “year-number.

cbchistlib.py
    #-- 1
    # [ if eltName is in form ->
    #     rawYear  :=  the corresponding value
    #   else ->
    #     return default ]
    try:
        rawYear = form[eltName].value
    except KeyError:
        return default

    #-- 2
    # [ if rawYear is a valid int ->
    #     return that int in year-number format
    #   else -> raise ScriptError ]
    try:
        yearNo = int(rawYear)
        return '%03d' % yearNo
    except lib.ScriptError:
        raise ScriptError("Not a valid %s: %s" % (desc, rawYear))