class TerritoryFenceValidator(Schema): """ TerritoryFence Validator""" name = validators.String(if_missing=None) type = validators.OneOf(["TERRITORY"], if_missing=None) country = validators.Regex(r"^[A-Z]{2}$", not_empty=True) administrative_area = validators.Regex(r"^[A-Z]{2}-[A-Z]{2}[A-Z]?$", if_missing=None) postal_code = validators.String(if_missing=None, if_empty=None) @staticmethod def _validate_python(value, _state): if not value["administrative_area"]: del value["administrative_area"] if not value["postal_code"]: del value["postal_code"]
def fields(self): username = ew.TextField(name='username', label='Desired Username', validator=fev.Regex(h.re_project_name)) username.validator._messages['invalid'] = ( 'Usernames must include only small letters, numbers, and dashes.' ' They must also start with a letter and be at least 3 characters' ' long.') fields = [ ew.TextField(name='display_name', label='Displayed Name', validator=fev.UnicodeString(not_empty=True)), username, ] if asbool(config.get('auth.require_email_addr', False)): fields.append( ew.TextField(name='email', label='Your e-mail', validator=fev.Email(not_empty=True))) fields += [ ew.PasswordField( name='pw', label='New Password', validator=fev.UnicodeString( not_empty=True, min=asint(tg.config.get('auth.min_password_len', 6)), max=asint(tg.config.get('auth.max_password_len', 30)))), ew.PasswordField(name='pw2', label='New Password (again)', validator=fev.UnicodeString(not_empty=True)), ] return fields
class fields(ew_core.NameList): project_description = ew.HiddenField(label='Public Description') neighborhood = ew.HiddenField(label='Neighborhood') private_project = ew.Checkbox(label="", attrs={'class': 'unlabeled'}) project_name = ew.InputField(label='Project Name', field_type='text', validator=formencode.All( fev.UnicodeString(not_empty=True, max=40), V.MaxBytesValidator(max=40))) project_unixname = ew.InputField( label='Short Name', field_type='text', validator=formencode.All( fev.String(not_empty=True), fev.MinLength(3), fev.MaxLength(15), fev.Regex( r'^[A-z][-A-z0-9]{2,}$', messages={ 'invalid': 'Please use only letters, numbers, and dashes 3-15 characters long.' }), NeighborhoodProjectTakenValidator())) tools = ew.CheckboxSet( name='tools', options=[ ## Required for Neighborhood functional tests to pass ew.Option(label='Wiki', html_value='wiki', selected=True) ])
class BurstNameForm(formencode.Schema): """ Validate Burst name string """ burst_name = formencode.All( validators.UnicodeString(not_empty=True), validators.Regex(regex=r"^[a-zA-Z\. _\-0-9]*$"))
class GitHubProjectForm(base.ProjectImportForm): project_name = fev.Regex( r'^[a-zA-Z0-9-_.]+$', not_empty=True, messages={ 'invalid': 'Valid symbols are: letters, numbers, dashes, underscores and periods', })
class BurstNameForm(formencode.Schema): """ Validate Recover Password Form """ burst_name = formencode.All(validators.UnicodeString(not_empty=True), validators.Regex(regex=r"^[a-zA-Z _\-0-9]*$"))
class UserRegistrationSchema(formencode.schema.Schema): login = Pipe(validators=[ _v.Regex(_LOGIN_NAME_RE, strip=True), _v.MaxLength(inspect(User).c.login.type.length), _v.NotEmpty(messages={'empty': 'Please enter an login'}), ]) name = Pipe(validators=[ _v.MaxLength(inspect(User).c.name.type.length), _v.NotEmpty(messages={'empty': 'Please enter your real name'}), ])
def __init__(self, request, tutorial): # TODO: Übungsleiter angeben. Aber wurde das jemals genutzt? formfields = [ #FormField('tutor', # label=u'Übungsleiter', size=64), FormField('place', label='Ort', size=64, value=tutorial.place if tutorial else None, required=True), FormField( 'wday', label='Wochentag', type='select', options=list( enumerate([ 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag' ])), required=True, value=int(tutorial.time.weekday()) if tutorial else None), FormField( 'timeofday', label='Uhrzeit', size=5, comment='(HH:MM oder HH)', validator=validators.Regex(r'^[012]?[0-9](:[0-5][0-9])?$'), required=True, value=tutorial.time.time() if tutorial else None), FormField('max_students', label='Max. Teilnehmerzahl', size=5, validator=validators.Int, required=True, value=tutorial.max_students if tutorial else None), FormField('comment', label='Kommentar', size=64, value=tutorial.comment if tutorial else None), FormField( 'is_special', label='Spezial', type='radio', options=[[1, 'Ja'], [0, 'Nein']], value=boolToValue(tutorial.is_special) if tutorial else 0) ] ObjectForm.__init__(self, tutorial, formfields, request, send=u'Ändern')
class fields(ew_core.NameList): display_name = ew.TextField( label='Displayed Name', validator=fev.UnicodeString(not_empty=True)) username = ew.TextField(label='Desired Username', validator=fev.Regex(h.re_path_portion)) username.validator._messages['invalid'] = ( 'Usernames must include only letters, numbers, and dashes.' ' They must also start with a letter and be at least 3 characters' ' long.') pw = ew.PasswordField(label='New Password', validator=fev.UnicodeString(not_empty=True, min=8)) pw2 = ew.PasswordField(label='New Password (again)', validator=fev.UnicodeString(not_empty=True))
class ArgumentApp(): @route("/int/<int:intarg>/float/<float:floatarg>/string/<stringarg>",Http.GET) def test(self,request,intarg,floatarg,stringarg,**kwargs): args = (intarg,floatarg,stringarg) return "%s" % map(lambda x: (type(x),x),args) @route("/validate/<int:rootId>/schema",Http.POST) @validate(schema=TestSchema()) def postValidateSchema(self,request,rootId,childId,**kwargs): return "%s - %s - %s" % (rootId,childId,kwargs) @route("/validate/<int:rootId>/custom",Http.POST) @validate(childId=validators.Regex(regex="^jacekf|test$")) def postValidateCustom(self,request,rootId,childId,**kwargs): return "%s - %s - %s" % (rootId,childId,kwargs)
def fields(self): fields = [ ew.HiddenField(name='app_id', label='App'), ew.TextField(name='name', label='Name', validator=fev.UnicodeString()), ew.TextField(name='shortname', label='Short Name', validator=All( fev.Regex(r"^[^\s\/\.]*$", not_empty=True, messages={ 'invalid': 'Shortname cannot contain space . or /', 'empty': 'You must create a short name for the forum.'}), UniqueForumShortnameValidator())), ew.TextField(name='parent', label='Parent Forum'), ew.TextField(name='description', label='Description', validator=fev.UnicodeString()), ew.TextField(name='monitoring_email', label='Monitoring Email', validator=fev.Email()), ew.Checkbox(name="members_only", label="Developer Only"), ew.Checkbox(name="anon_posts", label="Allow Anonymous Posts") ] return fields
def validate_with_regexp(regexp, value, not_empty=False, log=logging.getLogger(__name__)): value = str(value) log.debug('regexp validation: ' + str(regexp) + ' ~= ' + value) ret_value = True if (not_empty) and (len(value) == 0): ret_value = False re = validators.Regex(regex=regexp) try: re.to_python(value) except: ret_value = False log.debug(str(ret_value)) return ret_value
import tw2.core as twc import tw2.forms as twf from formencode.compound import All from formencode import validators name_validator = All(validators.NotEmpty(), validators.UnicodeString(), validators.Regex(r'[A-Za-z]')) phone_validator = All(validators.NotEmpty(), validators.UnicodeString(), validators.Regex(r'[0-9]')) class SubmitForm(twf.Form): class child(twf.TableLayout): nome = twf.TextField(size=15, validator=name_validator) telefono = twf.TextField(size=15, validator=phone_validator) submit = twf.SubmitButton(value='Submit') action = '/save'
class ShortURLAdminController(DefaultAdminController): shorturl_validators = All( validators.NotEmpty(), validators.Regex( r'^[-_a-zA-Z0-9]+$', messages={'invalid': 'must include only letters, numbers, dashes and underscores.'} ) ) @expose() def index(self, **kw): redirect(c.project.url() + 'admin/tools') @without_trailing_slash @expose('json:') def remove(self, shorturl, **kw): require_access(self.app, 'update') ShortUrl.query.remove({ 'app_config_id': self.app.config._id, 'short_name': shorturl}) return dict(status='ok') @expose('jinja:forgeshorturl:templates/form.html') @validate(dict(full_url=All(validators.URL(add_http=True), validators.NotEmpty()), short_url=shorturl_validators)) def add(self, short_url='', full_url='', description='', private='off', update=False, **kw): if update: require_access(self.app, 'update') else: require_access(self.app, 'create') if request.method == 'POST': if c.form_errors: error_msg = 'Error: ' for msg in list(c.form_errors): names = {'short_url': 'Short url', 'full_url': 'Full URL'} error_msg += '%s: %s ' % (names[msg], c.form_errors[msg]) flash(error_msg, 'error') redirect(request.referer) shorturl = ShortUrl.query.find({ 'app_config_id': self.app.config._id, 'short_name': short_url}).first() if shorturl is not None: if not update: flash('Short url %s already exists' % short_url, 'error') redirect(request.referer) else: msg = ('update short url %s from %s to %s' % (short_url, shorturl.full_url, full_url)) flash("Short url updated") else: shorturl = ShortUrl() shorturl.created = datetime.utcnow() shorturl.app_config_id = self.app.config._id msg = 'create short url %s for %s' % (short_url, full_url) flash("Short url created") shorturl.short_name = short_url shorturl.full_url = full_url shorturl.description = description shorturl.create_user = c.user._id shorturl.private = private == 'on' shorturl.last_updated = datetime.utcnow() M.AuditLog.log(msg) redirect(request.referer) return dict( app=self.app, url_len=len(ShortUrl.build_short_url(c.app, short_name='')))
class ClientAddForm(Schema): login = formencode.All(validators.UnicodeString(not_empty=True), UniqueUsername()) name = validators.String(not_empty=True) email = validators.Email(not_empty=True) mobile = validators.Regex(r'^[+]?[\d\ \-]{6,15}$')(not_empty=True)
class RootController(BaseController): """ The root controller for the tg-sample-contacts application. All the other controllers and WSGI applications should be mounted on this controller. For example:: panel = ControlPanelController() another_app = AnotherWSGIApplication() Keep in mind that WSGI applications shouldn't be mounted directly: They must be wrapped around with :class:`tg.controllers.WSGIAppController`. """ secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() def _before(self, *args, **kw): tmpl_context.project_name = "tgsamplecontacts" @expose('tgsamplecontacts.templates.form_error') def form_error(self, **kwargs): errors = [{ e[0]: e[1].args[0] } for e in tg.tmpl_context.form_errors.items()] values = tg.tmpl_context.form_values return dict(errors=errors, values=values) @expose('tgsamplecontacts.templates.contacts') def index(self): """Handle the front-page.""" user_id = get_user_id() contacts = DBSession.query(Contact).filter_by(user_id=user_id).all() return dict(page='contacts', contacts=contacts) @expose('tgsamplecontacts.templates.new_contact') def new_contact(self): """render the page with the form for adding a new user""" logged = False if get_user_id() is None else True return dict(page='New contact', logged=logged) @expose() @validate(validators=dict({ 'first_name': validators.String(max=80, not_empty=True), 'last_name': validators.String(max=80), 'number': validators.Regex(r'^\+?[-0-9 ]{10,20}$', not_empty=True) }), error_handler=form_error) def add_contact(self, first_name, last_name, number): contact = Contact() contact.first_name = first_name contact.last_name = last_name user = DBSession.query(User).filter_by(user_id=get_user_id()).one() contact.user = user n = Number() n.number = number n.contact = contact DBSession.add(n) DBSession.add(contact) redirect('/') @expose() def delete_contact(self, contact_id): """Deletes a single contact""" contact = DBSession.query(Contact).filter_by(id=contact_id).one() if contact.user_id == get_user_id(): DBSession.query(model.Number).filter_by(contact_id=contact.id).\ delete() DBSession.delete(contact) redirect('/') @expose('json') def export(self): contacts = DBSession.query(Contact).\ filter_by(user_id=get_user_id()).all() return {'contacts': contacts, 'user_id': get_user_id()} @expose('tgsamplecontacts.templates.login') def login(self, came_from=lurl('/'), failure=None, login=''): """Start the user login.""" if failure is not None: if failure == 'user-not-found': flash(_('User not found'), 'error') elif failure == 'invalid-password': flash(_('Invalid Password'), 'error') login_counter = request.environ.get('repoze.who.logins', 0) if failure is None and login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from, login=login) @expose() def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) flash(_('Welcome back, %s!') % request.identity['user'].user_name) # Do not use tg.redirect with tg.url as it will add the mountpoint # of the application twice. return HTTPFound(location=came_from) @expose() def post_logout(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on logout and say goodbye as well. """ flash(_('We hope to see you soon!')) return HTTPFound(location=came_from)
class TestSchema(Schema): allow_extra_fields = True childId = validators.Regex(regex="^jacekf|test$")
EDIT_FIELDS = ['name', 'url', 'is_read_open'] ADMIN_EDIT_FIELDS = ['is_active', 'subdomain'] SUBDOMAIN_VALIDATOR = formencode.All( fv.UnicodeString(not_empty=True, min=2, max=32, messages={ 'empty': 'Please enter a value', 'tooShort': 'Subdomains must be at least %(min)i characters.' }), fv.Regex(regex='^[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9]$', messages={ 'invalid': 'Names can only contain letters, numbers, and dashes (-)' })) SUBDOMAIN_VALIDATOR_EDIT = formencode.All( fv.UnicodeString(not_empty=False, min=2, max=32, messages={ 'empty': 'Please enter a value', 'tooShort': 'Subdomains must be at least %(min)i characters.' }), fv.Regex(regex='^[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9]$', messages={