Home

SqlAlchemy/Elixir validations crash test

install the thing

easy_install sqlalchemy_elixir_validations

use it in your entities:

  • Sqlalchemy:
from sqlalchemy_validations import *
people_table = Table(....)
class Person(object)
    pass
    
mapper(Person, people_table,
       extension=[Validator(
                            range_of('age', 0, 150),
                            format_of('phone', re.compile(r'\d{4}-?\d{4}'))
                            numericality_of('foo','bar','some_next_field')
                           )
                 ]
      )
  • Elixir:
from elixir_validations import *
class Person(Entity):
    username=Field(Unicode(30),nullable=False,index=True)
    email=Field(Unicode,nullable=False)
    age=Field(Integer,nullable=False)
    
    validates_uniqueness_of('username')
    validates_presence_of('username', 'email')
    validates_format_of('email',re.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])"))
    validates_numericality_of('age',integer_only = True)

Handling the validation errors

The model raises ValidationException which can be caught in your app's controller or whatever:

        entry = model.Page()
        # set entry attributes
        model.meta.Session.save(entry)      
        try:
            model.meta.Session.commit()
            h.flash('Page successfully created!')
            redirect_to(action = 'index')            
        except (ValidationException,IntegrityError),e:
            c.model_tags = h.ModelTags(c.entry)
            if type(e) == ValidationException:
                errors = e.errors
            else:
                errors = []
                h.flash(e.message)
            return formencode.htmlfill.render(\
                    render('/pages/new.mako'), \
                    errors = errors, 
                    defaults = request.params)                 

The important thing is the e.errors which is a dictionary of errors that can be passed directly to htmlfill for rendering.

Updated

Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.