Python wtforms.validators.StopValidation() Examples

The following are 17 code examples of wtforms.validators.StopValidation(). 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: file.py    From RSSNewsGAE with Apache License 2.0 8 votes vote down vote up
def __call__(self, form, field):
        if not (isinstance(field.data, FileStorage) and field.data):
            return

        filename = field.data.filename.lower()

        if isinstance(self.upload_set, Iterable):
            if any(filename.endswith('.' + x) for x in self.upload_set):
                return

            raise StopValidation(self.message or field.gettext(
                'File does not have an approved extension: {extensions}'
            ).format(extensions=', '.join(self.upload_set)))

        if not self.upload_set.file_allowed(field.data, filename):
            raise StopValidation(self.message or field.gettext(
                'File does not have an approved extension.'
            )) 
Example #2
Source File: core.py    From googleapps-message-recall with Apache License 2.0 7 votes vote down vote up
def _run_validation_chain(self, form, validators):
        """
        Run a validation chain, stopping if any validator raises StopValidation.

        :param form: The Form instance this field beongs to.
        :param validators: a sequence or iterable of validator callables.
        :return: True if validation was stopped, False otherwise.
        """
        for validator in validators:
            try:
                validator(form, self)
            except StopValidation as e:
                if e.args and e.args[0]:
                    self.errors.append(e.args[0])
                return True
            except ValueError as e:
                self.errors.append(e.args[0])

        return False 
Example #3
Source File: core.py    From jbox with MIT License 6 votes vote down vote up
def _run_validation_chain(self, form, validators):
        """
        Run a validation chain, stopping if any validator raises StopValidation.

        :param form: The Form instance this field beongs to.
        :param validators: a sequence or iterable of validator callables.
        :return: True if validation was stopped, False otherwise.
        """
        for validator in validators:
            try:
                validator(form, self)
            except StopValidation as e:
                if e.args and e.args[0]:
                    self.errors.append(e.args[0])
                return True
            except ValueError as e:
                self.errors.append(e.args[0])

        return False 
Example #4
Source File: __init__.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __call__(self, form, field):
        """
        e.g.::

            class ASNSearchForm(BaseForm):
                asn = StringField('可为空, 空格, 此外必须为正整数', validators=[PositiveInteger(allow_none=True)])

            class ASNForm(BaseForm):
                asn = StringField('必填正整数并转换后赋值', validators=[PositiveInteger()])

        """
        data = field.data.strip() if isinstance(field.data, str) else field.data
        fdata = get_int(data)
        if not ((data == '' or data is None) and self.allow_none) and (
                fdata is None or fdata < 1 and not (self.allow_0 and fdata == 0)):
            if self.message is None:
                self.message = '{}错误(非正整数{})'.format(field.label.text, '或0' if self.allow_0 else '')
            raise StopValidation(self.message)
        getattr(form, field.name).data = fdata 
Example #5
Source File: file.py    From jbox with MIT License 6 votes vote down vote up
def __call__(self, form, field):
        if not field.has_file():
            return

        filename = field.data.filename.lower()

        if isinstance(self.upload_set, (tuple, list)):
            ext = filename.rsplit('.', 1)[-1]
            if ext in self.upload_set:
                return
            message = '{} is not in the allowed extentions: {}'.format(
                ext, self.upload_set)
            raise StopValidation(self.message or message)

        if not self.upload_set.file_allowed(field.data, filename):
            raise StopValidation(self.message or
                                 'File does not have an approved extension') 
Example #6
Source File: __init__.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __call__(self, form, field):
        """
        e.g.::

            class SpecialRouteSearchForm(BaseForm):
                special_route = StringField('可为空, 空格, 有值时去除空白', validators=[StripString(allow_none=True)])

            class SpecialRouteForm(BaseForm):
                special_route = StringField('必填, 去除空白赋值', validators=[StripString()])

        """
        fdata = field.data
        if isinstance(fdata, str):
            if self.plain_text:
                fdata = get_plain_text(fdata)
            else:
                fdata = fdata.strip()
        if fdata == '' and not self.allow_none:
            if self.message is None:
                self.message = '{}不能为空{}'.format(field.label.text, '(纯文本)' if self.plain_text else '')
            raise StopValidation(self.message)
        getattr(form, field.name).data = fdata 
Example #7
Source File: core.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def _run_validation_chain(self, form, validators):
        """
        Run a validation chain, stopping if any validator raises StopValidation.

        :param form: The Form instance this field beongs to.
        :param validators: a sequence or iterable of validator callables.
        :return: True if validation was stopped, False otherwise.
        """
        for validator in validators:
            try:
                validator(form, self)
            except StopValidation as e:
                if e.args and e.args[0]:
                    self.errors.append(e.args[0])
                return True
            except ValueError as e:
                self.errors.append(e.args[0])

        return False 
Example #8
Source File: annotations.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def __call__(self, form: Dict[str, Any], field: Any) -> None:
        if not form["start_dttm"].data and not form["end_dttm"].data:
            raise StopValidation(_("annotation start time or end time is required."))
        if (
            form["end_dttm"].data
            and form["start_dttm"].data
            and form["end_dttm"].data < form["start_dttm"].data
        ):
            raise StopValidation(
                _("Annotation end time must be no earlier than start time.")
            ) 
Example #9
Source File: core.py    From jbox with MIT License 5 votes vote down vote up
def validate(self, form, extra_validators=tuple()):
        """
        Validates the field and returns True or False. `self.errors` will
        contain any errors raised during validation. This is usually only
        called by `Form.validate`.

        Subfields shouldn't override this, but rather override either
        `pre_validate`, `post_validate` or both, depending on needs.

        :param form: The form the field belongs to.
        :param extra_validators: A sequence of extra validators to run.
        """
        self.errors = list(self.process_errors)
        stop_validation = False

        # Call pre_validate
        try:
            self.pre_validate(form)
        except StopValidation as e:
            if e.args and e.args[0]:
                self.errors.append(e.args[0])
            stop_validation = True
        except ValueError as e:
            self.errors.append(e.args[0])

        # Run validators
        if not stop_validation:
            chain = itertools.chain(self.validators, extra_validators)
            stop_validation = self._run_validation_chain(form, chain)

        # Call post_validate
        try:
            self.post_validate(form, stop_validation)
        except ValueError as e:
            self.errors.append(e.args[0])

        return len(self.errors) == 0 
Example #10
Source File: core.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def post_validate(self, form, validation_stopped):
        """
        Override if you need to run any field-level validation tasks after
        normal validation. This shouldn't be needed in most cases.

        :param form: The form the field belongs to.
        :param validation_stopped:
            `True` if any validator raised StopValidation.
        """
        pass 
Example #11
Source File: core.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def validate(self, form, extra_validators=tuple()):
        """
        Validates the field and returns True or False. `self.errors` will
        contain any errors raised during validation. This is usually only
        called by `Form.validate`.

        Subfields shouldn't override this, but rather override either
        `pre_validate`, `post_validate` or both, depending on needs.

        :param form: The form the field belongs to.
        :param extra_validators: A sequence of extra validators to run.
        """
        self.errors = list(self.process_errors)
        stop_validation = False

        # Call pre_validate
        try:
            self.pre_validate(form)
        except StopValidation as e:
            if e.args and e.args[0]:
                self.errors.append(e.args[0])
            stop_validation = True
        except ValueError as e:
            self.errors.append(e.args[0])

        # Run validators
        if not stop_validation:
            chain = itertools.chain(self.validators, extra_validators)
            stop_validation = self._run_validation_chain(form, chain)

        # Call post_validate
        try:
            self.post_validate(form, stop_validation)
        except ValueError as e:
            self.errors.append(e.args[0])

        return len(self.errors) == 0 
Example #12
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 any error happen during process, we raise StopValidation here
        # to prevent "DataRequired" validator from clearing errors
        if self.errors:
            raise validators.StopValidation()
        super(ModelField, self).pre_validate(form) 
Example #13
Source File: file.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def __call__(self, form, field):
        if not (isinstance(field.data, FileStorage) and field.data):
            if self.message is None:
                message = field.gettext('This field is required.')
            else:
                message = self.message

            raise StopValidation(message) 
Example #14
Source File: core.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def post_validate(self, form, validation_stopped):
        """
        Override if you need to run any field-level validation tasks after
        normal validation. This shouldn't be needed in most cases.

        :param form: The form the field belongs to.
        :param validation_stopped:
            `True` if any validator raised StopValidation.
        """
        pass 
Example #15
Source File: core.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def validate(self, form, extra_validators=tuple()):
        """
        Validates the field and returns True or False. `self.errors` will
        contain any errors raised during validation. This is usually only
        called by `Form.validate`.

        Subfields shouldn't override this, but rather override either
        `pre_validate`, `post_validate` or both, depending on needs.

        :param form: The form the field belongs to.
        :param extra_validators: A sequence of extra validators to run.
        """
        self.errors = list(self.process_errors)
        stop_validation = False

        # Call pre_validate
        try:
            self.pre_validate(form)
        except StopValidation as e:
            if e.args and e.args[0]:
                self.errors.append(e.args[0])
            stop_validation = True
        except ValueError as e:
            self.errors.append(e.args[0])

        # Run validators
        if not stop_validation:
            chain = itertools.chain(self.validators, extra_validators)
            stop_validation = self._run_validation_chain(form, chain)

        # Call post_validate
        try:
            self.post_validate(form, stop_validation)
        except ValueError as e:
            self.errors.append(e.args[0])

        return len(self.errors) == 0 
Example #16
Source File: file.py    From jbox with MIT License 5 votes vote down vote up
def __call__(self, form, field):
        if not field.has_file():
            if self.message is None:
                message = field.gettext('This field is required.')
            else:
                message = self.message
            raise StopValidation(message) 
Example #17
Source File: core.py    From jbox with MIT License 5 votes vote down vote up
def post_validate(self, form, validation_stopped):
        """
        Override if you need to run any field-level validation tasks after
        normal validation. This shouldn't be needed in most cases.

        :param form: The form the field belongs to.
        :param validation_stopped:
            `True` if any validator raised StopValidation.
        """
        pass