def validator(ptype, required): from bs.lib.operations import wordlist """ Get the right validator for the ptype given """ if type2validator.get(ptype, False): if required: return twc.IntValidator(required=True) return twc.IntValidator() elif required: if wordlist.is_of_type(ptype, wordlist.FILE): if required: return twf.FileValidator(required=True) return twf.FileValidator() return twc.Validator(required=True) return None
class child(twf.TableLayout): hover_help = True email_filter = twf.HiddenField() id_filter = twf.HiddenField() user_Id= twf.TextField(help_text='Enter a user id.', validator=twc.IntValidator(required=True)) licenses = twf.MultipleSelectField(help_text='Licenses to assign.', options=[], validator=twc.Required) license_type = twf.SingleSelectField(help_text='Licenes Type.', value=0, options=[], validator=twc.Required) count = twf.SingleSelectField(help_text='Number of licenses.', value=1, options=[(i, i) for i in range(1,6)], validator=twc.Required)
def test_vld_leaf_fail(self): test = twc.Widget(validator=twc.IntValidator()).req() try: test._validate('x') assert (False) except twc.ValidationError: pass assert (test.value == 'x') assert (test.error_msg == 'Must be an integer')
def test_safe_validate_invalid(): v = twc.IntValidator() r = safe_validate(v, 'x') assert (r is twc.Invalid)
def test_vld_leaf_pass(self): test = twc.Widget(validator=twc.IntValidator()) assert (test.req()._validate('1') == 1)
def test_ve_subst(self): try: vld = twc.IntValidator(max=10) raise twc.ValidationError('toobig', vld) except twc.ValidationError, e: assert (str(e) == 'Cannot be more than 10')
class BasicTGController(TGController): @expose() @validate(ColonLessGenericValidator()) def validator_without_columns(self, **kw): return tg.request.validation['errors']['_the_form'] @expose('json:') @validate(validators={"some_int": validators.Int()}) def validated_int(self, some_int): assert isinstance(some_int, int) return dict(response=some_int) @expose('json:') @validate(validators={"a": validators.Int()}) def validated_and_unvalidated(self, a, b): assert isinstance(a, int) assert isinstance(b, unicode_text) return dict(int=a, str=b) @expose() @controller_based_validate() def validate_controller_based_validator(self, *args, **kw): return 'ok' @expose('json:') @validate(validators={ "a": validators.Int(), "someemail": validators.Email() }) def two_validators(self, a=None, someemail=None, *args): errors = tg.request.validation['errors'] values = tg.request.validation['values'] return dict(a=a, someemail=someemail, errors=str(errors), values=str(values)) @expose('json:') @validate(validators={"a": validators.Int()}) def with_default_shadow(self, a, b=None): """A default value should not cause the validated value to disappear""" assert isinstance(a, int), type(a) return { 'int': a, } @expose('json:') @validate(validators={"e": ColonValidator()}) def error_with_colon(self, e): errors = tg.request.validation['errors'] return dict(errors=str(errors)) @expose('json:') @validate( validators={ "a": validators.Int(), "b": validators.Int(), "c": validators.Int(), "d": validators.Int() }) def with_default_shadow_long(self, a, b=None, c=None, d=None): """A default value should not cause the validated value to disappear""" assert isinstance(a, int), type(a) assert isinstance(b, int), type(b) assert isinstance(c, int), type(c) assert isinstance(d, int), type(d) return { 'int': [a, b, c, d], } @expose() def display_form(self, **kwargs): return str(myform.render(values=kwargs)) @expose('json:') @validate(form=myform) def process_form(self, **kwargs): kwargs['errors'] = tg.request.validation['errors'] return dict(kwargs) @expose('json:') @validate(form=myform, error_handler=process_form) def send_to_error_handler(self, **kwargs): kwargs['errors'] = tg.request.validation['errors'] return dict(kwargs) @expose('json') def tw2form_error_handler(self, **kwargs): return dict(errors=tg.request.validation['errors']) @expose('json:') @validate(form=movie_form, error_handler=tw2form_error_handler) def send_tw2_to_error_handler(self, **kwargs): return 'passed validation' @expose() @validate({'param': tw2c.IntValidator()}, error_handler=validation_errors_response) def tw2_dict_validation(self, **kwargs): return 'NO_ERROR' @expose() @validate({'param': validators.Int()}, error_handler=validation_errors_response) def formencode_dict_validation(self, **kwargs): return 'NO_ERROR' @expose('text/plain') @validate(form=FormWithFieldSet, error_handler=tw2form_error_handler) def tw2_fieldset_submit(self, **kwargs): return 'passed validation' @expose() def set_lang(self, lang=None): tg.session['tg_lang'] = lang tg.session.save() return 'ok' @expose() @validate(validators=Pwd()) def password(self, pwd1, pwd2): if tg.request.validation['errors']: return "There was an error" else: return "Password ok!" @expose('json:') @before_render( lambda rem, params, output: output.update({'GOT_ERROR': 'HOOKED'})) def hooked_error_handler(self, *args, **kw): return dict(GOT_ERROR='MISSED HOOK') @expose() @validate({'v': validators.Int()}, error_handler=hooked_error_handler) def with_hooked_error_handler(self, *args, **kw): return dict(GOT_ERROR='NO ERROR') @expose('json') @validate({'v': validators.Int()}) def check_tmpl_context_compatibility(self, *args, **kw): return dict(tmpl_errors=str(tg.tmpl_context.form_errors), errors=str(tg.request.validation['errors'])) @expose() def error_handler(self, *args, **kw): return 'ERROR HANDLER!' @expose('json:') @validate(validators={"some_int": validators.Int()}, error_handler=error_handler) def validate_other_error_handler(self, some_int): return dict(response=some_int) def unexposed_error_handler(self, uid, **kw): return 'UID: %s' % uid @expose() @validate({ 'uid': validators.Int(), 'num': validators.Int() }, error_handler=unexposed_error_handler) def validate_unexposed(self, uid, num): return 'HUH' @expose() @validate({'num': validators.Int()}, error_handler=partial(unexposed_error_handler, uid=5)) def validate_partial(self, num): return 'HUH' @expose() @validate({ 'uid': tw2c.IntValidator(), 'num': tw2c.IntValidator() }, error_handler=error_handler_function) def validate_function(self, uid, num): return 'HUH' @expose() @validate({ 'uid': validators.Int(), 'num': validators.Int() }, error_handler=ErrorHandlerCallable()) def validate_callable(self, uid, num): return 'HUH' @expose() @validate({'uid': validators.Int()}, error_handler=ErrorHandlerCallable()) @validate({'num': validators.Int()}, error_handler=abort(412, error_handler=True)) def validate_multi(self, uid, num): return str(uid + num) @expose() @validate({'uid': validators.Int()}, error_handler=abort(412, error_handler=True)) def abort_error_handler(self): return 'HUH' @expose() @validate({'uid': validators.Int()}, error_handler=validation_errors_response) def validate_json_errors(self): return 'HUH' @expose() def validate_json_errors_complex_types(self, date): tg.request.validation.values = {'date': datetime.datetime.utcnow()} return validation_errors_response() @expose() @before_call(lambda remainder, params: params.setdefault('num', 5)) def hooked_error_handler(self, uid, num): return 'UID: %s, NUM: %s' % (uid, num) @expose() @validate(ThrowAwayValidationIntentValidator(), error_handler=abort(412, error_handler=True)) def throw_away_intent(self, uid): if tg.request.validation.exception: return 'ERROR' return 'UHU?' @expose() @validate(error_handler=hooked_error_handler) def passthrough_validation(self, uid): return str(uid) @expose() @validate({'uid': validators.Int()}, error_handler=hooked_error_handler) def validate_hooked(self, uid): return 'HUH' # Decorate validate_hooked with a controller wrapper Decoration.get_decoration(hooked_error_handler)\ ._register_controller_wrapper(ControllerWrapperForErrorHandler) @expose() def manually_handle_validation(self): # This is done to check that we don't break compatibility # with external modules that perform custom validation like tgext.socketio controller = self.__class__.validate_function args = (2, 'NaN') try: output = '' validate_params = get_params_with_argspec(controller, {}, args) params = DecoratedController._perform_validate( controller, validate_params) except validation_errors as inv: handler, output = DecoratedController._handle_validation_errors( controller, args, {}, inv, None) return output @expose(content_type='text/plain') @validate({'num': Convert(int, l_('This must be a number'))}, error_handler=validation_errors_response) def post_pow2(self, num=-1): return str(num * num) @expose(content_type='text/plain') @validate({'num': Convert(int, l_('This must be a number'), default=0)}, error_handler=validation_errors_response) def post_pow2_opt(self, num=-1): return str(num * num)
class BasicTGController(TGController): @expose('json') @validate(validators={"some_int": validators.Int()}) def validated_int(self, some_int): assert isinstance(some_int, int) return dict(response=some_int) @expose('json') @validate(validators={"a": validators.Int()}) def validated_and_unvalidated(self, a, b): assert isinstance(a, int) assert isinstance(b, unicode) return dict(int=a, str=b) @expose() @controller_based_validate() def validate_controller_based_validator(self, *args, **kw): return 'ok' @expose('json') @validate(validators={ "a": validators.Int(), "someemail": validators.Email }) def two_validators(self, a=None, someemail=None, *args): errors = pylons.tmpl_context.form_errors values = pylons.tmpl_context.form_values return dict(a=a, someemail=someemail, errors=str(errors), values=str(values)) @expose('json') @validate(validators={"a": validators.Int()}) def with_default_shadow(self, a, b=None): """A default value should not cause the validated value to disappear""" assert isinstance(a, int), type(a) return { 'int': a, } @expose('json') @validate(validators={"e": ColonValidator()}) def error_with_colon(self, e): errors = pylons.tmpl_context.form_errors return dict(errors=str(errors)) @expose('json') @validate( validators={ "a": validators.Int(), "b": validators.Int(), "c": validators.Int(), "d": validators.Int() }) def with_default_shadow_long(self, a, b=None, c=None, d=None): """A default value should not cause the validated value to disappear""" assert isinstance(a, int), type(a) assert isinstance(b, int), type(b) assert isinstance(c, int), type(c) assert isinstance(d, int), type(d) return { 'int': [a, b, c, d], } @expose() def display_form(self, **kwargs): return str(myform.render(values=kwargs)) @expose('json') @validate(form=myform) def process_form(self, **kwargs): kwargs['errors'] = pylons.tmpl_context.form_errors return dict(kwargs) @expose('json') @validate(form=myform, error_handler=process_form) def send_to_error_handler(self, **kwargs): kwargs['errors'] = pylons.tmpl_context.form_errors return dict(kwargs) @expose() def tw2form_error_handler(self, **kwargs): return dumps(dict(errors=pylons.tmpl_context.form_errors)) @expose('json') @validate(form=movie_form, error_handler=tw2form_error_handler) def send_tw2_to_error_handler(self, **kwargs): return 'passed validation' @expose() @validate({'param': tw2c.IntValidator()}) def tw2_dict_validation(self, **kwargs): return str(pylons.tmpl_context.form_errors) @expose() def set_lang(self, lang=None): pylons.session['tg_lang'] = lang pylons.session.save() return 'ok' @expose() @validate(validators=Pwd()) def password(self, pwd1, pwd2): if pylons.tmpl_context.form_errors: return "There was an error" else: return "Password ok!" @expose('json') @before_render( lambda rem, params, output: output.update({'GOT_ERROR': 'HOOKED'})) def hooked_error_handler(self, *args, **kw): return dict(GOT_ERROR='MISSED HOOK') @expose() @validate({'v': validators.Int()}, error_handler=hooked_error_handler) def with_hooked_error_handler(self, *args, **kw): return dict(GOT_ERROR='NO ERROR')
class child(twf.TableLayout): file = twf.FileField(validator=twf.FileValidator(required=True, extention='.html')) email = twf.TextField(validator=twc.EmailValidator(required=True)) # confirm_email = twf.TextField() class fred(twf.GridLayout): repetitions = 3 class child(twf.RowLayout): bob = twf.TextField() rob = twf.TextField() validator = twc.MatchValidator('bob', 'rob') select = twf.SingleSelectField(options=list(enumerate(opts)), validator=twc.Validator(required=True), item_validator=twc.IntValidator())