def clean(self): super(MyConfirmruleAdminForm, self).clean() if self.cleaned_data['ruletype'] == 'route': if not self.cleaned_data['idroute']: raise django_forms_util.ValidationError( _(u'For ruletype "route" it is required to indicate a route.' )) elif self.cleaned_data['ruletype'] == 'channel': if not self.cleaned_data['idchannel']: raise django_forms_util.ValidationError( _(u'For ruletype "channel" it is required to indicate a channel.' )) elif self.cleaned_data['ruletype'] == 'frompartner': if not self.cleaned_data['frompartner']: raise django_forms_util.ValidationError( _(u'For ruletype "frompartner" it is required to indicate a frompartner.' )) elif self.cleaned_data['ruletype'] == 'topartner': if not self.cleaned_data['topartner']: raise django_forms_util.ValidationError( _(u'For ruletype "topartner" it is required to indicate a topartner.' )) elif self.cleaned_data['ruletype'] == 'messagetype': if not self.cleaned_data['messagetype']: raise django_forms_util.ValidationError( _(u'For ruletype "messagetype" it is required to indicate a messagetype.' )) return self.cleaned_data
def clean(self, value): # Have to jump through a few hoops to make this reliable value = super(JSONFormField, self).clean(value) # allow an empty value on an optional field if value is None: return value ## Got to get rid of newlines for validation to work # Data newlines are escaped so this is safe value = value.replace('\r', '').replace('\n', '') if self.evaluate: json_globals = { # "safety" first! '__builtins__': None, 'datetime': datetime, } json_locals = { # value compatibility 'null': None, 'true': True, 'false': False, } try: value = json.dumps(eval(value, json_globals, json_locals), **self.encoder_kwargs) except Exception as e: # eval can throw many different errors raise util.ValidationError(str(e)) try: return json.loads(value, **self.decoder_kwargs) except ValueError as e: raise util.ValidationError(str(e))
def clean_email(self): """ Validates that a user exists with the given e-mail address and is not blocked. """ email = self.cleaned_data['email'] self.users_cache = User.objects.filter(email__iexact=email) if len(self.users_cache) == 0: raise util.ValidationError( _('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?' )) elif self.users_cache[0].is_active == False: try: last_admin = User.objects.filter( groups__permissions__codename='change_user').order_by( '-date_joined')[0] except: admin_email = '' else: admin_email = last_admin.email from core.templatetags.email import email_encode admin_email = email_encode(admin_email) raise util.ValidationError( mark_safe( _('Your account is blocked. Please, contact <a href="%s">administrator</a>.' ) % (admin_email)))
def clean(self, value): value = super(JsonFormField, self).clean(value) try: json.loads(value) except ValueError as e: raise util.ValidationError(e) return value
def clean(self, data, initial=None): super(NoExecFileField, self).clean(initial or data) if data != None: file_extension = data.name.split('.')[-1].lower() if file_extension in self.blocked_extensions: raise util.ValidationError( _('You are not allowed to attach executable files.')) return data
def clean(self): super(MyRouteAdminForm, self).clean() if self.cleaned_data[ 'fromchannel'] and self.cleaned_data['translateind'] != 2 and ( not self.cleaned_data['fromeditype'] or not self.cleaned_data['frommessagetype']): raise django_forms_util.ValidationError( _(u'When using an inchannel and not pass-through, both "fromeditype" and "frommessagetype" are required.' )) return self.cleaned_data
def clean(self, value): # First check if empty if value in fields.EMPTY_VALUES: if self.required: raise util.ValidationError(self.error_messages['required']) else: return super(PhoneField, self).clean(value) code, number = parse_phone(value) code_len = len(code) if code_len < 3 or code_len > 6: raise util.ValidationError(self.error_messages['code_length']) if not code.isdigit(): raise util.ValidationError(self.error_messages['code_digits']) if len(number.strip()) == 0: raise util.ValidationError(self.error_messages['number_length']) return smart_unicode('(%s) %s' % (code, number))
def clean(self): super(MyTranslateAdminForm, self).clean() blub = models.translate.objects.filter(fromeditype=self.cleaned_data['fromeditype'], frommessagetype=self.cleaned_data['frommessagetype'], alt=self.cleaned_data['alt'], frompartner=self.cleaned_data['frompartner'], topartner=self.cleaned_data['topartner']) if blub and (self.instance.pk is None or self.instance.pk != blub[0].id): raise django_forms_util.ValidationError( _('Combination of fromeditype,frommessagetype,alt,frompartner,topartner already exists.')) return self.cleaned_data
def clean(self, value): if value is None: return super(SkypeField, self).clean(value) value = value.strip() match = self.invalid_skype_chars_re.search(value) if not match is None: try: message = self.error_messages['wrong_symbol'] % value[ match.start()] except TypeError: message = self.error_messages['wrong_symbol'] raise util.ValidationError(message) return super(SkypeField, self).clean(value)
def clean(self, value): """ Validates that EUI() can be called on the input. Returns the result of EUI(). Returns None for empty values. """ value = super(MACAddressField, self).clean(value) if value in EMPTY_VALUES: return None try: value = EUI(str(value)) except (ValueError, TypeError, AddrFormatError): raise util.ValidationError(self.error_messages['invalid']) return value
def clean(self, value): """ Validates that the input is a valid BiblePassage. Returns a Unicode object. """ value = super(BiblePassageFormField, self).clean(value) if value == u'': return value try: return unicode(to_passage(value)) except InvalidPassage, e: raise util.ValidationError(e)
def clean(self, value): """ Validates the given value. Raises ValidationError for any errors. :param value: string :return: dict """ value = super(YAMLFormField, self).clean(value) # allow an empty value on an optional field if value is None or not len(value): return value # check of value try: value = yaml.load(value) except (yaml.scanner.ScannerError, yaml.parser.ParserError), e: try: message = util.ValidationError( u'%s: %s' % (self.default_error_messages.get( 'invalid', ''), unicode(e))) except: message = self.default_error_messages.get('invalid', '') raise util.ValidationError(message)
class JSONFormField(fields.Field): def __init__(self, *args, **kwargs): from fields import JSONEncoder, JSONDecoder self.evaluate = kwargs.pop('evaluate', False) self.encoder_kwargs = kwargs.pop('encoder_kwargs', {'cls': JSONEncoder}) self.decoder_kwargs = kwargs.pop('decoder_kwargs', { 'cls': JSONDecoder, 'parse_float': Decimal }) super(JSONFormField, self).__init__(*args, **kwargs) def clean(self, value): # Have to jump through a few hoops to make this reliable value = super(JSONFormField, self).clean(value) # allow an empty value on an optional field if value is None: return value ## Got to get rid of newlines for validation to work # Data newlines are escaped so this is safe value = value.replace('\r', '').replace('\n', '') if self.evaluate: json_globals = { # "safety" first! '__builtins__': None, 'datetime': datetime, } json_locals = { # value compatibility 'null': None, 'true': True, 'false': False, } try: value = json.dumps(eval(value, json_globals, json_locals), **self.encoder_kwargs) except Exception, e: # eval can throw many different errors raise util.ValidationError('%s (Caught "%s")' % (self.help_text, e)) try: json.loads(value, **self.decoder_kwargs) except ValueError, e: raise util.ValidationError('%s (Caught "%s")' % (self.help_text, e))
class YAMLFormField(fields.Field): """ YAML Form field """ default_error_messages = { 'invalid': u'Invalid YAML format', } def clean(self, value): """ Validates the given value. Raises ValidationError for any errors. :param value: string :return: dict """ value = super(YAMLFormField, self).clean(value) # allow an empty value on an optional field if value is None or not len(value): return value # check of value try: value = yaml.load(value) except (yaml.scanner.ScannerError, yaml.parser.ParserError), e: try: message = util.ValidationError( u'%s: %s' % (self.default_error_messages.get( 'invalid', ''), unicode(e))) except: message = self.default_error_messages.get('invalid', '') raise util.ValidationError(message) val = yaml.dump( value, Dumper=DjangoSafeDumper, allow_unicode=True, default_flow_style=True, ) try: val.index('...') raise util.ValidationError( self.default_error_messages.get('invalid', '')) except ValueError: pass return value
def clean(self, value): value = super(LatitudeField, self).clean(value) if not -90 <= value <= 90: raise util.ValidationError(self.error_messages['out_of_range']) return value