Python wtforms.validators.ValidationError() Examples

The following are 30 code examples of wtforms.validators.ValidationError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wtforms.validators , or try the search function .
Example #1
Source File: forms.py    From AUCR with GNU General Public License v3.0 6 votes vote down vote up
def validate_email(self, email):
        """Ensure no duplicate emails."""
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError(_('Please use a different email address.'))
        white_listed_email = None
        if current_app.config["ALLOWED_EMAIL_LIST"]:
            white_listed_email_list = current_app.config["ALLOWED_EMAIL_LIST"]
            for item in white_listed_email_list:
                item_length = len(item)
                test_email = self.email.data[-item_length:]
                user_email_address_domain = item[-item_length:]
                if user_email_address_domain == test_email:
                    white_listed_email = True
            if not white_listed_email:
                raise ValidationError(_('Please use a whitelisted email address.')) 
Example #2
Source File: fields.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def pre_validate(self, form):
        if self.data:
            if not current_user.is_authenticated:
                raise validators.ValidationError(
                    _('You must be authenticated'))
            elif not OrganizationPrivatePermission(self.data).can():
                raise validators.ValidationError(
                    _("Permission denied for this organization"))
            # Ensure either owner field or this field value is unset
            owner_field = form._fields[self.owner_field]
            if self.raw_data:
                owner_field.data = None
            elif getattr(form._obj, self.short_name) and not owner_field.data:
                pass
            else:
                self.data = None
        return True 
Example #3
Source File: fields.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def process_formdata(self, valuelist):
        if valuelist and valuelist[0]:
            value = valuelist[0]
            if isinstance(value, str):
                start, end = value.split(' - ')
                self.data = db.DateRange(
                    start=parse(start, yearfirst=True).date(),
                    end=parse(end, yearfirst=True).date(),
                )
            elif 'start' in value and 'end' in value:
                self.data = db.DateRange(
                    start=parse(value['start'], yearfirst=True).date(),
                    end=parse(value['end'], yearfirst=True).date(),
                )
            else:
                raise validators.ValidationError(
                    _('Unable to parse date range'))
        else:
            self.data = None 
Example #4
Source File: fields.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def process_formdata(self, valuelist):
        if valuelist:
            date_str = ' '.join(valuelist)
            if not date_str:
                self.data = None
                raise ValidationError(self.gettext('Please input a date/time value'))

            parse_kwargs = self.parse_kwargs.copy()
            if 'default' not in parse_kwargs:
                try:
                    parse_kwargs['default'] = self.default()
                except TypeError:
                    parse_kwargs['default'] = self.default
            try:
                self.data = parser.parse(date_str, **parse_kwargs)
            except ValueError:
                self.data = None
                raise ValidationError(self.gettext('Invalid date/time input')) 
Example #5
Source File: fields.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def pre_validate(self, form):
        invalid_dict, invalid_json = False, False
        try:
            result = loads(self.data)
        except Exception:
            invalid_json = True
        if self.json_only and invalid_json:
            raise ValidationError("Invalid json syntax.")
        try:
            result = literal_eval(self.data)
        except Exception:
            invalid_dict = True
        if invalid_dict and invalid_json:
            raise ValidationError("Invalid dictionary syntax.")
        if not isinstance(result, dict) and not self.json_only:
            raise ValidationError("This field only accepts dictionaries.")
        if app.contains_set(result):
            raise ValidationError("Sets are not allowed.")
        return True 
Example #6
Source File: fields.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def fetch_objects(self, oids):
        '''
        This methods is used to fetch models
        from a list of identifiers.

        Default implementation performs a bulk query on identifiers.

        Override this method to customize the objects retrieval.
        '''
        objects = self.model.objects.in_bulk(oids)
        if len(objects.keys()) != len(oids):
            non_existants = set(oids) - set(objects.keys())
            msg = _('Unknown identifiers: {identifiers}').format(
                identifiers=', '.join(str(ne) for ne in non_existants))
            raise validators.ValidationError(msg)

        return [objects[id] for id in oids] 
Example #7
Source File: user.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_job_number(self, field):
        if not TBUser.query.filter_by(job_number=field.data).first():
            raise ValidationError('工号{}不存在'.format(field.data)) 
Example #8
Source File: validators.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, form, field):
        if self.extractor.find_urls(field.data):
            raise validators.ValidationError(self.message) 
Example #9
Source File: validators.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, form, field):
        if not field.data:
            return
        other_field = form._fields.get(self.other_field_name)
        if other_field is None:
            raise Exception(
                'No field named "%s" in form' % self.other_field_name)
        if not bool(other_field.data):
            msg = field._('This field requires "%(name)s" to be set')
            raise validators.ValidationError(
                msg % {'name': field._(other_field.label.text)}) 
Example #10
Source File: forms.py    From DeepChatModels with MIT License 5 votes vote down vote up
def bad_chars(form, string_field):
    for c in r";'`":
        if c in string_field.data:
            raise ValidationError('DONT TYPE DAT') 
Example #11
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def pre_validate(self, form):
        if self.data:
            if current_user.is_anonymous:
                raise validators.ValidationError(
                    _('You must be authenticated'))
            elif not admin_permission and current_user.id != self.data.id:
                raise validators.ValidationError(
                    _('You can only set yourself as owner'))
        return True 
Example #12
Source File: forms.py    From indico-plugins with MIT License 5 votes vote down vote up
def validate_site_id_events(self, field):
        if self.site_id_general is not None and field is not None and self.site_id_general.data == field.data:
            raise ValidationError(_("Event statistics can't use the same Piwik site as global statistics")) 
Example #13
Source File: forms.py    From indico-plugins with MIT License 5 votes vote down vote up
def validate_owner_user(self, field):
        if not field.data:
            raise ValidationError(_("Unable to find this user in Indico."))
        if not next(iter_user_identities(field.data), None):
            raise ValidationError(_("This user does not have a suitable account to use Vidyo.")) 
Example #14
Source File: groupedselectfield.py    From radremedy with Mozilla Public License 2.0 5 votes vote down vote up
def pre_validate(self, form, choices=None):
        """
        Recurses on validation of choices that are
        contained within embedded iterables.
        """
        # See if we have default choices
        default_choices = choices is None

        # If we have choices provided (true for recursion on groups),
        # use those - otherwise, default to the top-level field choices.
        choices = choices or self.choices

        for value, label in choices:
            found = False

            # If the label in question is itself an iterable
            # (indicating the presence of an optgroup),
            # recurse on the choices in that optgroup.
            if isinstance(label, (list, tuple)):
                found = self.pre_validate(form, choices=label)

            # The second part of this also differs from the Gist -
            # we want to check value in self.data instead of value == self.data
            if found or value in self.data:
                return True

        # If we don't have any default choices at this point,
        # there's not really anything we can do.
        if not default_choices:
            return False

        raise ValidationError(self.gettext(u'Not a valid choice')) 
Example #15
Source File: fields.py    From eNMS with GNU General Public License v3.0 5 votes vote down vote up
def pre_validate(self, form):
        if self.python:
            try:
                parse(self.data)
            except Exception as exc:
                raise ValidationError(f"Wrong python expression ({exc}).")
        return True 
Example #16
Source File: user.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_job_number(self, field):
        if current_user.job_number == field.data:
            raise ValidationError('无法修改自己权限组') 
Example #17
Source File: role.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_role_id(self, field):
        if TBRole.query.filter(TBRole.role == self.role.data, TBRole.role_id != field.data).first():
            raise ValidationError('权限标识{}已存在'.format(self.role.data)) 
Example #18
Source File: role.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_role_id(self, field):
        if not TBRole.query.get(field.data):
            raise ValidationError('权限组异常, 无法删除') 
Example #19
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def _parse_value(self, key, value):
        if key not in self.extras.registered:
            return value
        expected = self.extras.registered[key]
        if expected in self.KNOWN_TYPES:
            try:
                return field_parse(self.KNOWN_TYPES[expected], value)
            except (validators.ValidationError, ValueError) as e:
                self.field_errors[key] = getattr(e, 'message', str(e))
        else:
            return value 
Example #20
Source File: forms.py    From RTB-CTF-Framework with MIT License 5 votes vote down vote up
def validate_username(self, username):
        if username.data != current_user.username:
            user = User.query.filter_by(username=username.data).first()
            if user:
                raise ValidationError(
                    "That username is taken. Please choose a different one."
                ) 
Example #21
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_formdata(self, valuelist):
        if not valuelist or len(valuelist) != 1 or not valuelist[0]:
            return
        specs = valuelist[0]
        model_field = getattr(self._form.model_class, self.name)
        if isinstance(specs, str):
            specs = {'id': specs}
        elif not specs.get('id', None):
            raise validators.ValidationError('Missing "id" field')

        if isinstance(model_field, db.ReferenceField):
            expected_model = str(model_field.document_type.__name__)
            if 'class' not in specs:
                specs['class'] = expected_model
            elif specs['class'] != expected_model:
                msg = 'Expect a "{0}" class but "{1}" was found'.format(
                    expected_model, specs['class']
                )
                raise validators.ValidationError(msg)
        elif isinstance(model_field, db.GenericReferenceField):
            if 'class' not in specs:
                msg = _('Expect both class and identifier')
                raise validators.ValidationError(msg)

        # No try/except required
        # In case of error, ValueError is raised
        # and is properly handled as form validation error
        model = db.resolve_model(specs['class'])
        oid = clean_oid(specs, model)

        try:
            self.data = model.objects.only('id').get(id=oid)
        except db.DoesNotExist:
            label = '{0}({1})'.format(model.__name__, oid)
            msg = _('{0} does not exists').format(label)
            raise validators.ValidationError(msg) 
Example #22
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_formdata(self, valuelist):
        if valuelist and len(valuelist) == 1 and valuelist[0]:
            try:
                id = clean_oid(valuelist[0], self.model)
                self.data = self.model.objects.get(id=id)
            except self.model.DoesNotExist:
                message = _('{0} does not exists').format(self.model.__name__)
                raise validators.ValidationError(message) 
Example #23
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def pre_validate(self, form):
        if not self.data:
            return
        for tag in self.data:
            if not tags.MIN_TAG_LENGTH <= len(tag) <= tags.MAX_TAG_LENGTH:
                message = _(
                    'Tag "%(tag)s" must be between %(min)d '
                    'and %(max)d characters long.',
                    min=tags.MIN_TAG_LENGTH,
                    max=tags.MAX_TAG_LENGTH, tag=tag)
                raise validators.ValidationError(message) 
Example #24
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def pre_validate(self, form):
        if self.data:
            try:
                uris.validate(self.data)
            except uris.ValidationError:
                raise validators.ValidationError(_('Invalid URL'))
        return True 
Example #25
Source File: fields.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_formdata(self, valuelist):
        self.data = []
        for name in valuelist:
            role = datastore.find_role(name)
            if role is not None:
                self.data.append(role)
            else:
                raise validators.ValidationError(
                    _('The role {role} does not exist').format(role=name)) 
Example #26
Source File: validators.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __call__(self, form, field):
        if field.data:
            try:
                json.loads(field.data)
            except JSONDecodeError as ex:
                message = self.message or 'JSON Validation Error: {}'.format(ex)
                raise ValidationError(
                    message=field.gettext(message.format(field.data))
                ) 
Example #27
Source File: validators.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __call__(self, form, field):
        try:
            other = form[self.fieldname]
        except KeyError:
            raise ValidationError(
                field.gettext("Invalid field name '%s'." % self.fieldname)
            )

        if field.data is None or other.data is None:
            return

        if field.data < other.data:
            message_args = {
                'other_label':
                    hasattr(other, 'label') and other.label.text or self.fieldname,
                'other_name': self.fieldname,
            }
            message = self.message
            if message is None:
                message = field.gettext(
                    'Field must be greater than or equal to %(other_label)s.' % message_args
                )
            else:
                message = message % message_args

            raise ValidationError(message) 
Example #28
Source File: fields.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def process_formdata(self, valuelist):
        if valuelist:
            date_str = ' '.join(valuelist)
            if not date_str:
                self.data = None
                raise ValidationError(self.gettext('Please input a date/time value'))

            parse_kwargs = self.parse_kwargs.copy()
            if 'default' not in parse_kwargs:
                try:
                    parse_kwargs['default'] = self.default()
                except TypeError:
                    parse_kwargs['default'] = self.default
            try:
                self.data = parser.parse(date_str, **parse_kwargs)
            except ValueError:
                self.data = None
                raise ValidationError(self.gettext('Invalid date/time input'))
            except TypeError:
                if not DATEUTIL_TYPEERROR_ISSUE:
                    raise

                # If we're using dateutil 2.2, then consider it a normal
                # ValidationError. Hopefully dateutil fixes this issue soon.
                self.data = None
                raise ValidationError(self.gettext('Invalid date/time input')) 
Example #29
Source File: fields.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def pre_validate(self, form):
        if not self.allow_blank or self.data is not None:
            for obj in self.queryset:
                if self.data == obj:
                    break
            else:
                raise ValidationError(self.gettext('Not a valid choice')) 
Example #30
Source File: fields.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def pre_validate(self, form):
        if self._invalid_formdata:
            raise ValidationError(self.gettext('Not a valid choice'))
        elif self.data:
            obj_list = list(x[1] for x in self._get_object_list())
            for v in self.data:
                if v not in obj_list:
                    raise ValidationError(self.gettext('Not a valid choice'))