Python wtforms.ValidationError() Examples

The following are 30 code examples of wtforms.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 , or try the search function .
Example #1
Source File: validators.py    From jbox with MIT License 8 votes vote down vote up
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
Example #2
Source File: base.py    From betterlifepsi with MIT License 6 votes vote down vote up
def validate(form, model, object_type="Object ", parent="parent", children="child", is_created=False):
        if is_created is False and \
                        form[parent] is not None and \
                        form[parent].data is not None and \
                        form[parent].data.id == model.id:
            raise ValidationError(gettext("Can not set %(ot)s's parent to itself[%(data)s]", ot=gettext(object_type), data=model))
        if is_created is False and \
                        form[parent] is not None and \
                        form[parent].data is not None and \
                        form[parent].data in getattr(model, children):
            raise ValidationError(gettext("Can not set %(ot)s's parent to it's child[%(data)s]", ot=gettext(object_type), data=form[parent].data))
        if hasattr(form, children) and \
                        form[children] is not None and \
                        form[children].data is not None and \
                        model in form[children].data:
            try:
                raise ValidationError(gettext("Can not set %(ot)s's child to itself[%(data)s]", ot=gettext(object_type), data=model))
            except BaseException:
                raise ValidationError(gettext("Can not set %(ot)s's child to itself", ot=gettext(object_type))) 
Example #3
Source File: receiving_test.py    From betterlifepsi with MIT License 6 votes vote down vote up
def test_delete_complete_receiving_not_allowed(self):
        def test_logic():
            from psi.app.models import Receiving, EnumValues
            from psi.app.views import ReceivingAdmin
            from psi.app.service import Info
            receiving = Receiving()
            complete_status = EnumValues.get(RECEIVING_COMPLETE_STATUS_KEY)
            receiving.status = complete_status
            db_session = Info.get_db().session
            receiving_admin = ReceivingAdmin(Receiving, db_session, name=lazy_gettext("Receiving"),
                                             category=lazy_gettext('Purchase'), menu_icon_type=ICON_TYPE_GLYPH,
                                             menu_icon_value='glyphicon-import')

            self.assertRaises(ValidationError, receiving_admin.on_model_delete, receiving)

        run_as_admin(self.test_client, test_logic) 
Example #4
Source File: validators.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
Example #5
Source File: alias_contact_manager.py    From app with MIT License 6 votes vote down vote up
def email_validator():
    """validate email address. Handle both only email and email with name:
    - ab@cd.com
    - AB CD <ab@cd.com>

    """
    message = "Invalid email format. Email must be either email@example.com or *First Last <email@example.com>*"

    def _check(form, field):
        email = field.data
        email = email.strip()
        email_part = email

        if "<" in email and ">" in email:
            if email.find("<") + 1 < email.find(">"):
                email_part = email[email.find("<") + 1 : email.find(">")].strip()

        if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", email_part):
            return

        raise ValidationError(message)

    return _check 
Example #6
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def protect(self):
        if request.method not in current_app.config['WTF_CSRF_METHODS']:
            return

        try:
            validate_csrf(self._get_csrf_token())
        except ValidationError as e:
            logger.info(e.args[0])
            self._error_response(e.args[0])

        if request.is_secure and current_app.config['WTF_CSRF_SSL_STRICT']:
            if not request.referrer:
                self._error_response('The referrer header is missing.')

            good_referrer = 'https://{0}/'.format(request.host)

            if not same_origin(request.referrer, good_referrer):
                self._error_response('The referrer does not match the host.')

        g.csrf_valid = True  # mark this request as CSRF valid 
Example #7
Source File: utils.py    From flask-security with MIT License 6 votes vote down vote up
def uia_email_mapper(identity):
    """ Used to match identity as an email.

    See :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.

    .. versionadded:: 3.4.0
    """

    # Fake up enough to invoke the WTforms email validator.
    class FakeField:
        pass

    email_validator = validators.Email(message="nothing")
    field = FakeField()
    field.data = identity
    try:
        email_validator(None, field)
    except ValidationError:
        return None
    return identity 
Example #8
Source File: franchise_purchase_order.py    From betterlifepsi with MIT License 6 votes vote down vote up
def on_model_change(self, form, model, is_created):
        from wtforms import ValidationError
        super(FranchisePurchaseOrderAdmin, self).on_model_change(form, model, is_created)
        for l in model.lines:
            if l.unit_price is None:
                l.unit_price = l.product.franchise_price
        if current_user.organization.type.code != const.FRANCHISE_STORE_ORG_TYPE_KEY:
            raise ValidationError(gettext("Your organization is not a franchise store and is not allowed to create franchise purchase order"))
        if current_user.organization.parent is None:
            raise ValidationError(gettext("Franchise purchase order creation failed, your organization does not have a valid parent organization"))
        if is_created:
                model.to_organization = current_user.organization.parent
        status = model.status
        if status.code == const.PO_ISSUED_STATUS_KEY:
            sales_order, incoming, expense = self.create_so_from_fpo(model)
            related_value = self.create_related_value(sales_order, model)
            db_util.save_objects_commit(sales_order, incoming, expense, related_value) 
Example #9
Source File: validators.py    From notifications-admin with MIT License 5 votes vote down vote up
def __call__(self, form, field):
        if field.data and not re.match(self.regex, field.data):
            raise ValidationError(self.message) 
Example #10
Source File: space.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_name(self, field):
        filters = {
            SpaceModel.status.notin_([SpaceModel.status_remove]),
            SpaceModel.name == field.data
        }
        space = SpaceModel.query.filter(*filters).first()
        # 新建时,环境名不可与
        if space and space.id != self.id:
            raise ValidationError('该Space已重名') 
Example #11
Source File: group.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_user_ids(self, field):
        current_app.logger.info(field.data)
        self.uid_roles = json.loads(field.data)

        user_ids = [uid_role['user_id'] for uid_role in self.uid_roles]
        roles = [uid_role['role'] for uid_role in self.uid_roles]
        # TODO validator roles
        # current_app.logger.info(user_ids)
        if UserModel.query.filter(UserModel.id.in_(user_ids)).count() != len(user_ids):
            raise ValidationError('存在未记录的用户添加到用户组') 
Example #12
Source File: group.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_group_name(self, field):
        env = TagModel.query.filter_by(name=field.data).filter_by(label='user_group').first()
        # 新建时,环境名不可与
        if env and env.id != self.group_id:
            raise ValidationError('该用户组已经配置过') 
Example #13
Source File: user.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_password(self, field):
        if field.data and not re.match(validator_regx_password, field.data):
            raise ValidationError('密码至少6个字符,至少1个大写字母,1个小写字母,1个数字') 
Example #14
Source File: validators.py    From notifications-admin with MIT License 5 votes vote down vote up
def __call__(self, form, field):

        if field.data == '':
            return

        from flask import url_for
        message = '''
            Enter a public sector email address or
            <a class="govuk-link govuk-link--no-visited-state" href="{}">find out who can use Notify</a>
        '''.format(url_for('main.who_can_use_notify'))
        if not is_gov_user(field.data.lower()):
            raise ValidationError(message) 
Example #15
Source File: validators.py    From notifications-admin with MIT License 5 votes vote down vote up
def __call__(self, form, field):

        if field.data == '':
            return

        try:
            validate_email_address(field.data)
        except InvalidEmailError:
            raise ValidationError(self.message) 
Example #16
Source File: validators.py    From notifications-admin with MIT License 5 votes vote down vote up
def __call__(self, form, field):
        if ',' in ''.join(Field(field.data).placeholders):
            raise ValidationError(self.message) 
Example #17
Source File: validators.py    From notifications-admin with MIT License 5 votes vote down vote up
def __call__(self, form, field):
        non_sms_characters = sorted(list(SanitiseSMS.get_non_compatible_characters(field.data)))
        if non_sms_characters:
            raise ValidationError(
                'You cannot use {} in text messages. {} will not show up properly on everyone’s phones.'.format(
                    formatted_list(non_sms_characters, conjunction='or', before_each='', after_each=''),
                    ('It' if len(non_sms_characters) == 1 else 'They')
                )
            ) 
Example #18
Source File: validators.py    From notifications-admin with MIT License 5 votes vote down vote up
def __call__(self, form, field):
        if field.data and not re.match(self.regex, field.data):
            raise ValidationError(self.message) 
Example #19
Source File: environment.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_status(self, field):
        if field.data and int(field.data) not in [1, 2]:
            raise ValidationError('非法的状态') 
Example #20
Source File: organization.py    From betterlifepsi with MIT License 5 votes vote down vote up
def on_model_delete(self, model):
        """
        Validate model with child organization should not be deleted
        :param model: The model to delete
        :return: None
        """
        if len(model.all_children) > 0:
            raise ValidationError(gettext('Can not delete an organization with child organisation exists')) 
Example #21
Source File: user.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_username(self, field):
        """ username muse be unique """
        if UserModel.query.filter(UserModel.username == field.data, UserModel.status != -1).count():
            raise ValidationError('此用户名已经被注册') 
Example #22
Source File: user.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_password(self, field):
        if field.data and not re.match(validator_regx_password, field.data):
            raise ValidationError('密码至少6个字符,至少1个大写字母,1个小写字母,1个数字') 
Example #23
Source File: user.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_email(self, field):
        if UserModel.query.filter_by(email=field.data).first():
            raise ValidationError('Email already register') 
Example #24
Source File: server.py    From walle-web with Apache License 2.0 5 votes vote down vote up
def validate_name(self, field):
        server = ServerModel.query.filter_by(name=field.data).first()
        # 新建时,环境名不可与
        if server and server.id != self.id:
            raise ValidationError('该Server已重名') 
Example #25
Source File: util_test.py    From indico-plugins with MIT License 5 votes vote down vote up
def test_validate_business(data, valid):
    field = MagicMock(data=data)
    if valid:
        validate_business(None, field)
    else:
        with pytest.raises(ValidationError):
            validate_business(None, field) 
Example #26
Source File: util.py    From indico-plugins with MIT License 5 votes vote down vote up
def validate_business(form, field):
    """Valiates a PayPal business string.

    It can either be an email address or a paypal business account ID.
    """
    if not is_valid_mail(field.data, multi=False) and not re.match(r'^[a-zA-Z0-9]{13}$', field.data):
        raise ValidationError(_('Invalid email address / paypal ID')) 
Example #27
Source File: forms.py    From flask-todolist with MIT License 5 votes vote down vote up
def validate_username(self, field):
        if User.query.filter_by(username=field.data).first():
            raise ValidationError("Username already in use.") 
Example #28
Source File: forms.py    From flask-todolist with MIT License 5 votes vote down vote up
def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError("Email already registered.") 
Example #29
Source File: validators.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def __call__(self, form, field):
        try:
            obj = self.get_session().query(self.model)\
                .filter(self.column == field.data).one()
            if not hasattr(form, '_obj') or not form._obj == obj:
                if self.message is None:
                    self.message = field.gettext('Already exists.')
                raise ValidationError(self.message)
        except NoResultFound:
            pass 
Example #30
Source File: forms.py    From stack with MIT License 5 votes vote down vote up
def __call__(self, form, field):
        api_filter = form['api'].data
        network = form['network'].data
        if network == 'twitter' and api_filter == 'track' or api_filter == 'follow':
            if field.data is None or field.data == '':
                raise ValidationError(self.message)