### install() Source: https://www.formencode.org/en/latest/_sources/modules/doctest_xml_compare.txt Installs the XML comparison logic into the environment. ```APIDOC ## install() ### Description Configures the environment to use the XML comparison logic provided by this module. ``` -------------------------------- ### ForEach validator usage Source: https://www.formencode.org/en/latest/modules/foreach.html Examples demonstrating how to apply validators to list items, including the use of multiple arguments. ```python ForEach(Int(), OneOf([1, 2, 3])) ``` ```python ForEach(All(Int(), OneOf([1, 2, 3]))) ``` -------------------------------- ### TimeConverter Usage Source: https://www.formencode.org/en/latest/modules/validators.html Examples of converting time strings to tuples and handling AM/PM formatting. ```python >>> tim = TimeConverter() >>> tim.to_python('8:30') (8, 30) >>> tim.to_python('20:30') (20, 30) >>> tim.to_python('30:00') Traceback (most recent call last): ... Invalid: You must enter an hour in the range 0-23 >>> tim.to_python('13:00pm') Traceback (most recent call last): ... Invalid: You must enter an hour in the range 1-12 >>> tim.to_python('12:-1') Traceback (most recent call last): ... Invalid: You must enter a minute in the range 0-59 >>> tim.to_python('12:02pm') (12, 2) >>> tim.to_python('12:02am') (0, 2) >>> tim.to_python('1:00PM') (13, 0) >>> tim.from_python((13, 0)) '13:00:00' >>> tim2 = tim(use_ampm=True, use_seconds=False) >>> tim2.from_python((13, 0)) '1:00pm' >>> tim2.from_python((0, 0)) '12:00am' >>> tim2.from_python((12, 0)) '12:00pm' ``` -------------------------------- ### Generate complex HTML structures Source: https://www.formencode.org/en/latest/modules/htmlgen.html Examples of nesting multiple tags and using the 'c' keyword for content, as well as simple tag generation. ```python >>> str(html.html( ... html.head(html.title("Page Title")), ... html.body( ... bgcolor='#000066', ... text='#ffffff', ... c=[html.h1('Page Title'), ... html.p('Hello world!')], ... ))) 'Page Title

Page Title

Hello world!

' >>> str(html.a(href='#top')('return to top')) 'return to top' ``` -------------------------------- ### Testing Language Translations Source: https://www.formencode.org/en/latest/Validator.html Examples of how to structure tests for new language translations. ```python ne = formencode.validators.NotEmpty() [...] def test_de(): _test_lang("de", "Bitte einen Wert eingeben") ``` ```python def test_(): _test_lang("", "") ``` -------------------------------- ### Define a SQLObject class Source: https://www.formencode.org/en/latest/_sources/Design.txt An example of a domain object class definition using SQLObject, which FormEncode intentionally avoids coupling with validation logic. ```python class Address(SQLObject): fname = StringCol(notNull=True) lname = StringCol(notNull=True) mi = StringCol() ``` -------------------------------- ### Nested Dictionary and List Mapping Source: https://www.formencode.org/en/latest/Validator.html Example of how flat form keys are decoded into a nested Python dictionary structure. ```python {'names': [{'fname': "John", 'lname': "Doe"}, {'fname': "Jane", 'lname': 'Brown'}, "Tim Smith"], 'action': {None: "save", 'option': "overwrite", 'confirm': "yes"}, } ``` -------------------------------- ### Populate HTML form fields with FillingParser Source: https://www.formencode.org/en/latest/modules/htmlfill.html Demonstrates initializing FillingParser with a dictionary of defaults and feeding it HTML to populate input, select, textarea, and checkbox elements. ```python >>> defaults = dict(name='Bob Jones', ... occupation='Crazy Cultist', ... address='14 W. Canal\nNew Guinea', ... living='no', ... nice_guy=0) >>> parser = FillingParser(defaults) >>> parser.feed(''' ... ... ... ... ... ''') >>> parser.close() >>> print (parser.text()) ``` -------------------------------- ### Initializing a New Language Catalog Source: https://www.formencode.org/en/latest/Validator.html Commands to initialize a new translation catalog for FormEncode. ```bash $ svn co http://svn.formencode.org/FormEncode/trunk/ $ easy_install Babel $ python setup.py init_catalog -l $ emacs formencode/i18n//LC_MESSAGES/FormEncode.po # or whatever # editor you prefer make the translation $ python setup.py compile_catalog -l ``` -------------------------------- ### Download FormEncode as zip Source: https://www.formencode.org/en/latest/_sources/download.txt Direct link to download the current master branch as a zip archive. ```text https://github.com/formencode/formencode/zipball/master ``` -------------------------------- ### Using Wrapper for Custom Conversion Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates wrapping functions for conversion and validation, including handling of empty values. ```python >>> def downcase(v): ... return v.lower() >>> wrap = Wrapper(convert_to_python=downcase) >>> wrap.to_python('This') 'this' >>> wrap.from_python('This') 'This' >>> wrap.to_python('') is None True >>> wrap2 = Wrapper( ... convert_from_python=downcase, empty_value=lambda value: value) >>> wrap2.from_python('This') 'this' >>> wrap2.to_python('') '' >>> wrap2.from_python(1) Traceback (most recent call last): ... Invalid: 'int' object has no attribute 'lower' >>> wrap3 = Wrapper(validate_python=int) >>> wrap3.to_python('1') '1' >>> wrap3.to_python('a') Traceback (most recent call last): ... Invalid: invalid literal for int()... ``` -------------------------------- ### Create HTML tags with chaining Source: https://www.formencode.org/en/latest/modules/htmlgen.html Demonstrates creating an anchor tag with attributes and content using chained calls. ```python >>> str(html.a(href='http://yahoo.com')('')) '<Yahoo>' ``` -------------------------------- ### Using Constant Converter Source: https://www.formencode.org/en/latest/modules/validators.html Shows how to force conversion to a specific constant value and how to use it within an Any validator. ```python # Any evaluates sub validators in reverse order for to_python fromEmailValidator = Any( Constant('unknown@localhost'), Email()) ``` ```python >>> Constant('X').to_python('y') 'X' ``` -------------------------------- ### DateConverter Usage Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates basic date conversion and error handling with the default DateConverter. ```python >>> d = DateConverter() >>> d.to_python('12/3/09') datetime.date(2009, 12, 3) >>> d.to_python('12/3/2009') datetime.date(2009, 12, 3) >>> d.to_python('2/30/04') Traceback (most recent call last): ... Invalid: That month only has 29 days >>> d.to_python('13/2/05') Traceback (most recent call last): ... Invalid: Please enter a month from 1 to 12 >>> d.to_python('1/1/200') Traceback (most recent call last): ... Invalid: Please enter a four-digit year after 1899 ``` -------------------------------- ### Configure Schema with RequireIfPresent Source: https://www.formencode.org/en/latest/modules/validators.html Shows how to integrate RequireIfPresent into a Schema using chained_validators and if_missing settings. ```python class PhoneInput(Schema): phone = PhoneNumber() phone_type = String(if_missing=None) chained_validators = [RequireIfPresent('phone_type', present='phone')] ``` -------------------------------- ### Validate with Any validator Source: https://www.formencode.org/en/latest/modules/compound.html Demonstrates using the Any validator to accept the first successful validation among multiple options. ```python >>> from formencode.validators import DictConverter >>> av = Any(validators=[DictConverter({2: 1}), ... DictConverter({3: 2}), DictConverter({4: 3})]) >>> av.to_python(3) 2 >>> av.from_python(2) 3 ``` -------------------------------- ### Clone the FormEncode repository Source: https://www.formencode.org/en/latest/_sources/community.txt Use this command to retrieve the latest source code from the official GitHub repository. ```bash git clone git://github.com/formencode/formencode.git ``` -------------------------------- ### Convert to Unicode String with UnicodeString Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates converting inputs to Unicode strings, including handling of None, empty lists, and custom encodings. ```python >>> UnicodeString().to_python(None) == '' True >>> UnicodeString().to_python([]) == '' True >>> UnicodeString(encoding='utf-7').to_python('Ni Ni Ni') == 'Ni Ni Ni' True ``` -------------------------------- ### TimeConverter with datetime.time Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates using TimeConverter to return datetime.time objects. ```python >>> v = TimeConverter(use_datetime=True) >>> a = v.to_python('18:00') >>> a datetime.time(18, 0) >>> b = v.to_python('30:00') Traceback (most recent call last): ... Invalid: You must enter an hour in the range 0-23 >>> v2 = TimeConverter(prefer_ampm=True, use_datetime=True) >>> v2.from_python(a) '6:00:00pm' >>> v3 = TimeConverter(prefer_ampm=True, ... use_seconds=False, use_datetime=True) >>> a = v3.to_python('18:00') >>> a datetime.time(18, 0) >>> v3.from_python(a) '6:00pm' >>> a = v3.to_python('18:00:00') Traceback (most recent call last): ... Invalid: You may not enter seconds ``` -------------------------------- ### DateConverter with European Style Source: https://www.formencode.org/en/latest/modules/validators.html Shows how to configure DateConverter to use a specific month style. ```python >>> d = DateConverter(month_style='dd/mm/yyyy') >>> date = d.to_python('12/3/09') >>> date datetime.date(2009, 3, 12) >>> d.from_python(date) '12/03/2009' ``` -------------------------------- ### Configure Validators via Instantiation or Subclassing Source: https://www.formencode.org/en/latest/Validator.html Validators can be configured by passing arguments during instantiation or by creating a subclass with class-level attributes. ```python >>> plain = validators.Regex(regex='^[a-zA-Z]+$') >>> # and... >>> class Plain(validators.Regex): ... regex = '^[a-zA-Z]+$' >>> plain = Plain() ``` -------------------------------- ### Using DictConverter for dictionary-based mapping Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates converting values using a dictionary mapping and handling missing keys with custom error messages. ```python >>> dc = DictConverter({1: 'one', 2: 'two'}) >>> dc.to_python(1) 'one' >>> dc.from_python('one') 1 >>> dc.to_python(3) Traceback (most recent call last): .... Invalid: Enter a value from: 1; 2 >>> dc2 = dc(hideDict=True) >>> dc2.hideDict True >>> dc2.dict {1: 'one', 2: 'two'} >>> dc2.to_python(3) Traceback (most recent call last): .... Invalid: Choose something >>> dc.from_python('three') Traceback (most recent call last): .... Invalid: Nothing in my dictionary goes by the value 'three'. Choose one of: 'one'; 'two' ``` -------------------------------- ### htmlfill.render(form, defaults, errors=None, prefix=None, auto_insert_errors=True, use_all_keys=False, **kw) Source: https://www.formencode.org/en/latest/htmlfill.html Renders an HTML form string by filling in default values and error messages. ```APIDOC ## htmlfill.render(form, defaults, errors=None, prefix=None, auto_insert_errors=True, use_all_keys=False, **kw) ### Description Fills out an HTML form string with provided default values and error messages. It parses the HTML to locate input elements and injects values or error tags accordingly. ### Parameters - **form** (string) - Required - The HTML form string to be processed. - **defaults** (dict) - Optional - A dictionary of default values where keys correspond to input names. - **errors** (dict) - Optional - A dictionary of error messages where keys correspond to input names. - **prefix** (string) - Optional - A prefix to prepend to field names. - **auto_insert_errors** (bool) - Optional - If True, automatically inserts errors above the associated input field if not explicitly handled by tags. - **use_all_keys** (bool) - Optional - If True, raises an AssertionError if there are unused keys in defaults or errors. ### Example ```python from formencode import htmlfill form = '' defaults = {'fname': 'Joe'} htmlfill.render(form, defaults) # Returns: '' ``` ``` -------------------------------- ### Validate URLs with FormEncode Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates URL validation with various configurations, including automatic scheme addition and existence checking. ```python >>> u = URL(add_http=True) >>> u.to_python('foo.com') 'http://foo.com' >>> u.to_python('http://hahaha.ha/bar.html') 'http://hahaha.ha/bar.html' >>> u.to_python('http://xn--m7r7ml7t24h.com') 'http://xn--m7r7ml7t24h.com' >>> u.to_python('http://xn--c1aay4a.xn--p1ai') 'http://xn--c1aay4a.xn--p1ai' >>> u.to_python('http://foo.com/test?bar=baz&fleem=morx') 'http://foo.com/test?bar=baz&fleem=morx' >>> u.to_python('http://foo.com/login?came_from=http%3A%2F%2Ffoo.com%2Ftest') 'http://foo.com/login?came_from=http%3A%2F%2Ffoo.com%2Ftest' >>> u.to_python('http://foo.com:8000/test.html') 'http://foo.com:8000/test.html' >>> u.to_python('http://foo.com/something\nelse') Traceback (most recent call last): ... Invalid: That is not a valid URL >>> u.to_python('https://test.com') 'https://test.com' >>> u.to_python('http://test') Traceback (most recent call last): ... Invalid: You must provide a full domain name (like test.com) >>> u.to_python('http://test..com') Traceback (most recent call last): ... Invalid: That is not a valid URL >>> u = URL(add_http=False, check_exists=True) >>> u.to_python('http://google.com') 'http://google.com' >>> u.to_python('google.com') Traceback (most recent call last): ... Invalid: You must start your URL with http://, https://, etc >>> u.to_python('https://httpbin.org/status/404') Traceback (most recent call last): ... Invalid: The server responded that the page could not be found >>> u.to_python('http://this.domain.does.not.exist.example.org/test.html') ... Traceback (most recent call last): ... Invalid: An error occured when trying to connect to the server: ... ``` ```python >>> URL(require_tld=False).to_python('http://localhost') 'http://localhost' ``` ```python >>> URL(allow_idna=True).to_python( ... 'http://\u0433\u0443\u0433\u043b.\u0440\u0444') 'http://xn--c1aay4a.xn--p1ai' >>> URL(allow_idna=True, add_http=True).to_python( ... '\u0433\u0443\u0433\u043b.\u0440\u0444') 'http://xn--c1aay4a.xn--p1ai' >>> URL(allow_idna=False).to_python( ... 'http://\u0433\u0443\u0433\u043b.\u0440\u0444') Traceback (most recent call last): ... Invalid: That is not a valid URL ``` -------------------------------- ### render(html, defaults=None, errors=None, ...) Source: https://www.formencode.org/en/latest/_sources/modules/htmlfill.txt Renders HTML with form values filled in from defaults and error messages applied. ```APIDOC ## render(html, defaults=None, errors=None, ...) ### Description Fills in HTML forms with provided default values and error messages. ### Parameters - **html** (string) - The HTML content to process. - **defaults** (dict) - Optional. A dictionary of default values to fill in the form fields. - **errors** (dict) - Optional. A dictionary of error messages to associate with form fields. ``` -------------------------------- ### Validate simple integer input Source: https://www.formencode.org/en/latest/Validator.html Demonstrates using the Int validator to convert a string to an integer and handling invalid input with an exception. ```python >>> import formencode >>> from formencode import validators >>> validator = validators.Int() >>> validator.to_python("10") 10 >>> validator.to_python("ten") Traceback (most recent call last): ... Invalid: Please enter an integer value ``` -------------------------------- ### Define a Schema using class syntax Source: https://www.formencode.org/en/latest/modules/schema.html Use class-based syntax to define validators for specific fields within a schema. ```python class MySchema(Schema): name = Validators.PlainText() phone = Validators.PhoneNumber() ``` -------------------------------- ### Convert values to integers with Int Source: https://www.formencode.org/en/latest/modules/validators.html Illustrates using the Int validator to convert inputs to integers with optional range constraints. ```python >>> Int.to_python('10') 10 >>> Int.to_python('ten') Traceback (most recent call last): ... Invalid: Please enter an integer value >>> Int(min=5).to_python('6') 6 >>> Int(max=10).to_python('11') Traceback (most recent call last): ... Invalid: Please enter a number that is 10 or smaller ``` -------------------------------- ### xml_compare(x1, x2, reporter=None) Source: https://www.formencode.org/en/latest/modules/doctest_xml_compare.html Compares two XML structures for equality, optionally using a reporter to handle differences. ```APIDOC ## xml_compare(x1, x2, reporter=None) ### Description Compares two XML objects (x1 and x2) and returns the result of the comparison. An optional reporter can be provided to capture or report differences. ### Parameters - **x1** (object) - Required - The first XML object to compare. - **x2** (object) - Required - The second XML object to compare. - **reporter** (object) - Optional - A reporter instance to handle comparison output. ``` -------------------------------- ### Validate non-empty input with NotEmpty Source: https://www.formencode.org/en/latest/modules/validators.html Ensures the input is not empty, treating Python falsey values as invalid except for zero. ```python >>> ne = NotEmpty(messages=dict(empty='enter something')) >>> ne.to_python('') Traceback (most recent call last): ... Invalid: enter something >>> ne.to_python(0) 0 ``` -------------------------------- ### Convert strings to booleans with StringBool Source: https://www.formencode.org/en/latest/modules/validators.html Shows how StringBool converts various string inputs into boolean values based on configured true/false lists. ```python >>> s = StringBool() >>> s.to_python('yes'), s.to_python('no') (True, False) >>> s.to_python(1), s.to_python('N') (True, False) >>> s.to_python('ye') Traceback (most recent call last): ... Invalid: Value should be 'true' or 'false' ``` -------------------------------- ### Validate with All validator Source: https://www.formencode.org/en/latest/modules/compound.html Demonstrates using the All validator to chain multiple DictConverter instances, where all must succeed. ```python >>> from formencode.validators import DictConverter >>> av = All(validators=[DictConverter({2: 1}), ... DictConverter({3: 2}), DictConverter({4: 3})]) >>> av.to_python(4) 1 >>> av.from_python(1) 4 ``` -------------------------------- ### xml_compare(expected, actual) Source: https://www.formencode.org/en/latest/_sources/modules/doctest_xml_compare.txt Compares two XML structures to determine if they are equivalent for testing purposes. ```APIDOC ## xml_compare(expected, actual) ### Description Compares the expected XML structure against the actual XML structure. Returns True if they match, otherwise raises an assertion error or returns False depending on implementation. ### Parameters - **expected** (XML) - Required - The expected XML structure. - **actual** (XML) - Required - The actual XML structure to compare against. ``` -------------------------------- ### Render form with default values Source: https://www.formencode.org/en/latest/_sources/htmlfill.txt Basic usage of htmlfill.render to populate an input field with a default value. ```python >>> from formencode import htmlfill >>> form = '' >>> defaults = {'fname': 'Joe'} >>> htmlfill.render(form, defaults) '' ``` -------------------------------- ### Generalize validation with a helper function Source: https://www.formencode.org/en/latest/Validator.html A reusable function that accepts a prompt and a validator instance to handle input validation cycles. ```python >>> def valid_input(prompt, validator): ... while 1: ... try: ... value = input(prompt) ... return validator.to_python(value) ... except formencode.Invalid as e: ... print(e) >>> valid_input('Enter your email: ', validators.Email()) Enter your email: bob An email address must contain a single @ Enter your email: bob@nowhere.com 'bob@nowhere.com' ``` -------------------------------- ### add_prefix(prefix, name) Source: https://www.formencode.org/en/latest/_sources/modules/htmlrename.txt Adds a prefix to a specific field name. ```APIDOC ## add_prefix(prefix, name) ### Description Adds a prefix to a specific field name. ### Parameters - **prefix** (string) - The prefix to add. - **name** (string) - The original field name. ``` -------------------------------- ### Validator Configuration Source: https://www.formencode.org/en/latest/Validator.html Validators can be configured via instance variables during instantiation or by subclassing. Common options include if_empty, not_empty, strip, if_invalid, if_invalid_python, accept_python, and if_missing. ```APIDOC ## Validator Configuration ### Description Validators use instance variables to store customization information. You can use either subclassing or normal instantiation to set these. ### Options - **if_empty** (any) - Returned if input evaluates to false (empty list, string, None), but not 0 or False. Applies to .to_python(). - **not_empty** (boolean) - If true, raises an error if an empty value is provided. - **strip** (boolean) - If true and input is a string, the string is stripped before empty tests. - **if_invalid** (any) - Returned when .to_python() would raise an Invalid exception. - **if_invalid_python** (any) - Returned when .from_python() is invalid. - **accept_python** (boolean) - If True (default), _validate_python() and _validate_other() are not called during .from_python(). - **if_missing** (any) - Used when a field is missing in a schema, preventing an error. ``` -------------------------------- ### Convert values to booleans with Bool Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates the Bool validator which returns True or False based on the existence of the input value. ```python >>> Bool.to_python(0) False >>> Bool.to_python(1) True >>> Bool.to_python('') False >>> Bool.to_python(None) False ``` -------------------------------- ### Validate ByteString length and conversion Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates using ByteString to enforce length constraints and handle empty inputs. ```python >>> ByteString(min=2).to_python('a') Traceback (most recent call last): ... Invalid: Enter a value 2 characters long or more >>> ByteString(max=10).to_python('xxxxxxxxxxx') Traceback (most recent call last): ... Invalid: Enter a value not more than 10 characters long >>> ByteString().from_python(None) '' >>> ByteString().from_python([]) '' >>> ByteString().to_python(None) '' >>> ByteString(min=3).to_python(None) Traceback (most recent call last): ... Invalid: Please enter a value >>> ByteString(min=1).to_python('') Traceback (most recent call last): ... Invalid: Please enter a value ``` -------------------------------- ### Validate a list of items with ForEach Source: https://www.formencode.org/en/latest/Validator.html Use ForEach to apply a schema to each entry in a list of dictionaries. ```python >>> class BookSchema(formencode.Schema): ... id = validators.Int() ... title = validators.ByteString(not_empty=True) >>> validator = formencode.ForEach(BookSchema()) ``` -------------------------------- ### Verify matching fields with FieldsMatch Source: https://www.formencode.org/en/latest/modules/validators.html Ensures multiple fields contain identical values, commonly used for password confirmation inputs. ```python >>> f = FieldsMatch('pass', 'conf') >>> sorted(f.to_python({'pass': 'xx', 'conf': 'xx'}).items()) [('conf', 'xx'), ('pass', 'xx')] >>> f.to_python({'pass': 'xx', 'conf': 'yy'}) Traceback (most recent call last): ... Invalid: conf: Fields do not match ``` -------------------------------- ### Set translation domain and language Source: https://www.formencode.org/en/latest/_sources/i18n.txt Configures the translation domain and target languages for FormEncode. ```python formencode.api.set_stdtranslation(domain="FormEncode", languages=["de"]) ``` -------------------------------- ### Instantiate and use SimpleFormValidator Source: https://www.formencode.org/en/latest/modules/schema.html Wrap a validation function with SimpleFormValidator to validate input dictionaries. ```python from formencode.schema import SimpleFormValidator validator = SimpleFormValidator(validate) validator.to_python({'country': 'US', 'state': ''}, None) sorted(validator.to_python({'state': 'IL'}, None).items()) ``` -------------------------------- ### Validate with Pipe validator Source: https://www.formencode.org/en/latest/modules/compound.html Demonstrates using the Pipe validator to pass values through a sequence of validators in a left-to-right order for to_python. ```python >>> from formencode.validators import DictConverter >>> pv = Pipe(validators=[DictConverter({1: 2}), ... DictConverter({2: 3}), DictConverter({3: 4})]) >>> pv.to_python(1) 4 >>> pv.from_python(4) 1 ``` -------------------------------- ### Validate and Convert Country Names Source: https://www.formencode.org/en/latest/modules/national.html Converts country names to ISO-3166 abbreviations and vice versa using CountryValidator. ```python >>> CountryValidator.to_python('Germany') 'DE' >>> CountryValidator.to_python('Finland') 'FI' >>> CountryValidator.to_python('UNITED STATES') 'US' >>> CountryValidator.to_python('Krakovia') Traceback (most recent call last): ... Invalid: That country is not listed in ISO 3166 >>> CountryValidator.from_python('DE') 'Germany' >>> CountryValidator.from_python('FI') 'Finland' ``` -------------------------------- ### Handle validation exceptions in a loop Source: https://www.formencode.org/en/latest/Validator.html Uses a loop to repeatedly prompt for input until a valid integer is provided, catching the Invalid exception for feedback. ```python >>> def get_integer(): ... while 1: ... try: ... value = input('Enter a number: ') ... return validator.to_python(value) ... except formencode.Invalid as e: ... print (e) ... >>> get_integer() Enter a number: ten Please enter an integer value Enter a number: 10 10 ``` -------------------------------- ### Implement a custom SecurePassword validator Source: https://www.formencode.org/en/latest/Validator.html A complete implementation of a custom validator inheriting from FancyValidator, demonstrating whitespace stripping and custom validation logic. ```python >>> import re >>> class SecurePassword(validators.FancyValidator): ... ... min = 3 ... non_letter = 1 ... letter_regex = re.compile(r'[a-zA-Z]') ... ... messages = { ... 'too_few': 'Your password must be longer than %(min)i ' ... 'characters long', ... 'non_letter': 'You must include at least %(non_letter)i ' ... 'characters in your password', ... } ... ... def _convert_to_python(self, value, state): ... # _convert_to_python gets run before _validate_python. ... # Here we strip whitespace off the password, because leading ... # and trailing whitespace in a password is too elite. ... return value.strip() ... ... def _validate_python(self, value, state): ... if len(value) < self.min: ... raise formencode.Invalid(self.message("too_few", state, ... min=self.min), ... value, state) ... non_letters = self.letter_regex.sub('', value) ... if len(non_letters) < self.non_letter: ... raise formencode.Invalid(self.message("non_letter", state, ... non_letter=self.non_letter), ... value, state) ``` -------------------------------- ### formencode.htmlfill.render Source: https://www.formencode.org/en/latest/_sources/htmlfill.txt Fills out HTML form elements with provided default values and error messages. ```APIDOC ## formencode.htmlfill.render(form, defaults=None, errors=None, **kw) ### Description Fills out HTML form elements (input, select, textarea) with default values and error messages. It parses the provided HTML string and injects values based on the name attributes of the elements. ### Parameters - **form** (string) - Required - The HTML string containing the form elements to be filled. - **defaults** (dict) - Optional - A dictionary mapping field names to their default values. - **errors** (dict) - Optional - A dictionary mapping field names to error messages. - **use_all_keys** (bool) - Optional - If True, raises an AssertionError if there are unused keys in defaults or errors. ### Request Example ```python from formencode import htmlfill form = '' defaults = {'fname': 'Joe'} htmlfill.render(form, defaults) ``` ### Response - **Returns** (string) - The modified HTML string with filled values and error messages. ``` -------------------------------- ### formencode.htmlfill_schemabuilder.SchemaBuilder Source: https://www.formencode.org/en/latest/modules/htmlfill_schemabuilder.html A class that can be passed to htmlfill.render to process schema-defining statements during HTML rendering. ```APIDOC ## SchemaBuilder ### Description An extension class for `htmlfill` that can be passed to the `listen` argument of `htmlfill.render` to parse out schema-defining statements. ``` -------------------------------- ### Using MinLength validator Source: https://www.formencode.org/en/latest/modules/validators.html Validates that the length of a sequence meets the minimum requirement, noting that empty values are skipped unless not_empty is set. ```python >>> min5 = MinLength(5) >>> min5.to_python('12345') '12345' >>> min5.from_python('12345') '12345' >>> min5.to_python('1234') Traceback (most recent call last): ... Invalid: Enter a value at least 5 characters long >>> min5(accept_python=False).from_python('1234') Traceback (most recent call last): ... Invalid: Enter a value at least 5 characters long >>> min5.to_python([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> min5.to_python([1, 2, 3]) Traceback (most recent call last): ... Invalid: Enter a value at least 5 characters long >>> min5.to_python(5) Traceback (most recent call last): ... Invalid: Invalid value (value with length expected) ``` -------------------------------- ### Validate MAC addresses Source: https://www.formencode.org/en/latest/modules/validators.html Use the MACAddress validator to verify hardware addresses. The add_colons option can be used to format the output. ```python >>> mac = MACAddress() >>> mac.to_python('aa:bb:cc:dd:ee:ff') 'aabbccddeeff' >>> mac.to_python('aa:bb:cc:dd:ee:ff:e') Traceback (most recent call last): ... Invalid: A MAC address must contain 12 digits and A-F; the value you gave has 13 characters >>> mac.to_python('aa:bb:cc:dd:ee:fx') Traceback (most recent call last): ... Invalid: MAC addresses may only contain 0-9 and A-F (and optionally :), not 'x' >>> MACAddress(add_colons=True).to_python('aabbccddeeff') 'aa:bb:cc:dd:ee:ff' ``` -------------------------------- ### Validate conditional field presence with RequireIfPresent Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates using RequireIfPresent to enforce field requirements based on the presence of another field. ```python >>> from formencode import validators >>> v = validators.RequireIfPresent('phone_type', present='phone') >>> v.to_python(dict(phone_type='', phone='510 420 4577')) Traceback (most recent call last): ... Invalid: You must give a value for phone_type >>> v.to_python(dict(phone='')) {'phone': ''} ``` -------------------------------- ### Configuring Builtin Gettext Usage Source: https://www.formencode.org/en/latest/Validator.html Control whether FormEncode uses the builtin gettext function. ```python Validator.use_builtin_gettext == True # True is default ``` -------------------------------- ### Configure FileUploadKeeper in HTML and Python Source: https://www.formencode.org/en/latest/modules/validators.html Use FileUploadKeeper to manage file uploads and static fields in a form scheme. Requires the legacy-cgi package for Python 3.13+. ```html ``` ```python class MyScheme(Scheme): myfield = FileUploadKeeper() ``` -------------------------------- ### Handle optional attributes Source: https://www.formencode.org/en/latest/modules/htmlgen.html Shows that setting an attribute to None results in the attribute being omitted from the generated HTML. ```python >>> str(html.a(href='http://www.yahoo.com', name=None, ... c='Click Here')) 'Click Here' ``` -------------------------------- ### Declarative Source: https://www.formencode.org/en/latest/modules/declarative.html Base class for declarative objects in FormEncode. It allows classes to be used as instances, where constructor keyword arguments override instance variables. Supports __unpackargs__ for positional argument mapping and __classinit__ for class creation hooks. ```APIDOC ## class formencode.declarative.Declarative(*args, **kw) ### Description Base class for declarative objects. Classes inheriting from this can be instantiated with keyword arguments that override instance variables. ### Parameters - **args** (tuple) - Optional - Positional arguments mapped via __unpackargs__. - **kw** (dict) - Optional - Keyword arguments that override instance variables. ``` -------------------------------- ### ForEach(args, **kw) Source: https://www.formencode.org/en/latest/modules/foreach.html A validator that applies one or more validators to each item in a list. ```APIDOC ## class formencode.foreach.ForEach ### Description Use this to apply a validator or converter to each item in a list. It attempts to convert the entire list even if errors are encountered, collecting them into an Invalid exception. ### Parameters - **args** (Validator/Converter) - One or more validators to apply to each item. - **convert_to_list** (bool) - Optional. If True, forces the input to be a list (non-lists become one-element lists, None becomes an empty list). ### Usage Example ```python # Apply Int() and OneOf() to each item in a list ForEach(Int(), OneOf([1, 2, 3])) # Equivalent to using All() ForEach(All(Int(), OneOf([1, 2, 3]))) ``` ``` -------------------------------- ### Configure chained_validators for multiple fields Source: https://www.formencode.org/en/latest/Validator.html Demonstrates applying multiple FieldsMatch validators to a schema to validate confirmation fields. ```python >>> chained_validators = [ ... validators.FieldsMatch('password', ... 'password_confirm'), ... validators.FieldsMatch('email', ... 'email_confirm')] ``` -------------------------------- ### Define a Registration schema Source: https://www.formencode.org/en/latest/Validator.html Defines a schema using various validators and chained_validators to enforce field constraints and cross-field consistency. ```python >>> class Registration(formencode.Schema): ... first_name = validators.ByteString(not_empty=True) ... last_name = validators.ByteString(not_empty=True) ... email = validators.Email(resolve_domain=True) ... username = formencode.All(validators.PlainText(), ... UniqueUsername()) ... password = SecurePassword() ... password_confirm = validators.ByteString() ... chained_validators = [validators.FieldsMatch( ... 'password', 'password_confirm')] ``` -------------------------------- ### Create a custom SecurePassword validator Source: https://www.formencode.org/en/latest/Validator.html Subclasses FancyValidator to check input against a dictionary file, raising an Invalid exception if a match is found. ```python >>> class SecurePassword(formencode.FancyValidator): ... words_filename = '/usr/share/dict/words' ... def _convert_to_python(self, value, state): ... f = open(self.words_filename) ... lower = value.strip().lower() ... for line in f: ... if line.strip().lower() == lower: ... raise formencode.Invalid( ... 'Please do not base your password on a ' ... 'dictionary term', value, state) ... return value ``` -------------------------------- ### formencode.htmlfill_schemabuilder.parse_schema(form) Source: https://www.formencode.org/en/latest/modules/htmlfill_schemabuilder.html Parses an HTML form to extract and return the schema defined within it. ```APIDOC ## parse_schema(form) ### Description Parses an HTML form string or object to extract the schema defined within it and returns a `Schema` object. ### Parameters - **form** (string/object) - Required - The HTML form content to be parsed for schema definitions. ``` -------------------------------- ### Using IndexListConverter for list indexing Source: https://www.formencode.org/en/latest/modules/validators.html Converts indices to list values and handles out-of-range or missing items. ```python >>> index = IndexListConverter(['zero', 'one', 'two']) >>> index.to_python(0) 'zero' >>> index.from_python('zero') 0 >>> index.to_python('1') 'one' >>> index.to_python(5) Traceback (most recent call last): Invalid: Index out of range >>> index(not_empty=True).to_python(None) Traceback (most recent call last): Invalid: Please enter a value >>> index.from_python('five') Traceback (most recent call last): Invalid: Item 'five' was not found in the list ``` -------------------------------- ### Validate Email Addresses Source: https://www.formencode.org/en/latest/modules/validators.html Demonstrates email validation using the Email validator, including domain resolution options. Requires dnspython for domain resolution. ```python >>> e = Email() >>> e.to_python(' test@foo.com ') 'test@foo.com' >>> e.to_python('test') Traceback (most recent call last): ... Invalid: An email address must contain a single @ >>> e.to_python('test@foobar') Traceback (most recent call last): ... Invalid: The domain portion of the email address is invalid (the portion after the @: foobar) >>> e.to_python('test@foobar.com.5') Traceback (most recent call last): ... Invalid: The domain portion of the email address is invalid (the portion after the @: foobar.com.5) >>> e.to_python('test@foo..bar.com') Traceback (most recent call last): ... Invalid: The domain portion of the email address is invalid (the portion after the @: foo..bar.com) >>> e.to_python('test@.foo.bar.com') Traceback (most recent call last): ... Invalid: The domain portion of the email address is invalid (the portion after the @: .foo.bar.com) >>> e.to_python('nobody@xn--m7r7ml7t24h.com') 'nobody@xn--m7r7ml7t24h.com' >>> e.to_python('o*reilly@test.com') 'o*reilly@test.com' >>> e = Email(resolve_domain=True) >>> e.resolve_domain True >>> e.to_python('doesnotexist@colorstudy.com') 'doesnotexist@colorstudy.com' >>> e.to_python('test@nyu.edu') 'test@nyu.edu' >>> # NOTE: If you do not have dnspython installed this example won't work: >>> e.to_python('test@thisdomaindoesnotexistithinkforsure.com') Traceback (most recent call last): ... Invalid: The domain of the email address does not exist (the portion after the @: thisdomaindoesnotexistithinkforsure.com) >>> e.to_python('test@google.com') 'test@google.com' >>> e = Email(not_empty=False) >>> e.to_python('') ``` -------------------------------- ### classinstancemethod Source: https://www.formencode.org/en/latest/modules/declarative.html A decorator that allows a method to behave as a class method when called from a class, and as an instance method when called from an instance. ```APIDOC ## formencode.declarative.classinstancemethod(func) ### Description Decorator that enables a method to accept 'self' and 'cls' arguments, where one is None depending on the invocation context (class vs instance). ### Parameters - **func** (callable) - Required - The method to decorate. ``` -------------------------------- ### Validate Credit Card Security Code with CreditCardSecurityCode Source: https://www.formencode.org/en/latest/modules/validators.html Verifies that the security code length matches the requirements for the provided credit card type. ```python >>> code = CreditCardSecurityCode() >>> sorted(code.to_python({'ccType': 'visa', 'ccCode': '111'}).items()) [('ccCode', '111'), ('ccType', 'visa')] >>> code.to_python({'ccType': 'visa', 'ccCode': '1111'}) Traceback (most recent call last): ... Invalid: ccCode: Invalid credit card security code length ``` -------------------------------- ### Implement a custom validator Source: https://www.formencode.org/en/latest/Validator.html Creates a custom validator by subclassing FancyValidator to check for unique values against an external source. ```python >>> # We don't really have a database of users, so we'll fake it: >>> usernames = [] >>> class UniqueUsername(formencode.FancyValidator): ... def _convert_to_python(self, value, state): ... if value in usernames: ... raise formencode.Invalid( ... 'That username already exists', ... value, state) ... return value ```