Exemple #1
0
def validate_acceptable_range_eur(form, field):
    try:
        e = int(field.data)
        if e < 0:
            raise validators.StopValidation("Something went wrong")
    except (TypeError, ValueError):
        raise validators.StopValidation("Something went wrong")
Exemple #2
0
def validate_id_range(form, field):
    try:
        identity = int(field.data)
        if identity < 1:
            raise validators.StopValidation("Something went wrong")
    except (TypeError, ValueError):
        raise validators.StopValidation("Something went wrong")
Exemple #3
0
 def validate_type(self, type):
     try:
         FeedbackType.query.filter(FeedbackType.id == type.data).one()
     except NoResultFound:
         raise validators.StopValidation('不存在该分类!')
     except MultipleResultsFound:
         raise validators.StopValidation('不存在该分类!')
Exemple #4
0
    def validate_mobile(self, field):
        if errors.err_ok != validate_phone(field.data):
            raise validators.StopValidation(message=u'手机号错误')

        user = Account.get_by_alias(field.data)
        if user and not user.need_verify():
            raise validators.StopValidation(message=u'手机号已被注册 试试直接登录吧')
Exemple #5
0
def validate_range_max_stake(form, field):
    try:
        s = float(field.data)
        if s < 0.0 or s > 100.0:
            raise validators.StopValidation("Something went wrong")
    except (TypeError, ValueError):
        raise validators.StopValidation("Something went wrong")
Exemple #6
0
 def __call__(self, form, field):
     if hasattr(form, 'day'):
         if not form.day.data and not form.month.data and not form.year.data:
             raise validators.StopValidation(self.message)
     else:
         if not form.month.data and not form.year.data:
             raise validators.StopValidation(self.message)
Exemple #7
0
def validate_acceptable_range_cent(form, field):
    try:
        c = int(field.data)
        if c < 0 or c > 99:
            raise validators.StopValidation("Something went wrong")
    except (TypeError, ValueError):
        raise validators.StopValidation("Something went wrong")
Exemple #8
0
def validate_min_max_stake(form, field):
    try:
        stake = int(100 * form.stake.data)
        if stake > float(form.max_stake.data) * 100:
            raise validators.StopValidation("Your stake is larger than the smallest maximum stake of the selected offers " + form.max_stake.data + " eur")
    except (TypeError, ValueError):
        raise validators.StopValidation("Please, select a stake")
Exemple #9
0
    def __call__(self, form, field):
        """Call when request post data from some form. \
If this validation fails, it will be raise StopValidation

		Arguments:
			form {Object/Class} -- Form which some field has this validators
			field {Object/Class} -- Field which has this validators

		Raises:
			validators.StopValidation -- Raise when validation fails
		"""
        if not hasattr(self.model, self.field_name):
            message = "Terjadi kesalahan, hubungi administrator!"
            field.errors = []
            raise validators.StopValidation(message)

        if field.data and isinstance(field.data, string_types) and \
         field.data.strip():
            obj = getattr(self.model, self.field_name)
            user = self.model.query.filter(obj == field.data).first()
            if user:
                field.errors = []
                if self.message is None:
                    message = "Data {} sudah ada!".format(self.field_name)
                else:
                    message = self.message
                raise validators.StopValidation(message)
Exemple #10
0
    def __call__(self, form, field):
        """Call when request post data from some form. \
If this validation fails, it will be raise StopValidation

		Arguments:
			form {Object/Class} -- Form which some field has this validators
			field {Object/Class} -- Field which has this validators

		Raises:
			validators.StopValidation -- Raise when validation fails
		"""
        if field.data and isinstance(field.data, string_types) and \
         field.data.strip():
            if self.same_field not in form.data:
                message = "Terjadi kesalahan, hubungi administrator!"
                field.errors = []
                raise validators.StopValidation(message)

            if form.data[self.same_field] != field.data:
                if self.message is None:
                    message = "Data tidak sama dengan {}!".format(
                        self.same_field)
                else:
                    message = self.message
                field.errors = []
                raise validators.StopValidation(message)
Exemple #11
0
 def validate_friend_id(self, friend):
     if friend.data == token.id:
         raise validators.StopValidation('参数传递错误!')
     friend_name = db.session.query(
         User.userName).filter(User.id == friend.data).scalar()
     if not friend_name:
         raise validators.StopValidation('不存在此用户')
     self.friend_name = friend_name
Exemple #12
0
def validate_stake_places(form, field):
    if field.data == None:
        raise validators.StopValidation("Field cannot be empty")
    balance_str = str(field.data)
    if balance_str.find(".") != -1:
        split_eur_cent = balance_str.split(".")
        if len(split_eur_cent[1]) > 2:
            raise validators.StopValidation("Only two decimal places allowed")
 def InviteCodeValid(self, form, field):
     self.invite_code = db.session.query(InviteCode).get(field.data)
     if not self.invite_code or self.invite_code.disabled:
         raise validators.StopValidation(
             "Sorry, the invite code you entered is invalid.")
     elif self.invite_code.recipient_id:
         raise validators.StopValidation(
             "Sorry, the invite code you entered has already been claimed.")
Exemple #14
0
 def validate_name(self,name):
     word_list = string.punctuation
     for i in word_list:
         if i in name.data:
             raise validators.StopValidation('聊天室名称不能带有特殊字符!')
     queryset=db.session.query(ChatRoom.id).filter(ChatRoom.name==name.data).first()
     if queryset:
         raise validators.StopValidation('聊天室名称已经被抢先注册了!')
Exemple #15
0
    def __call__(self, form, field):
        try:
            Decimal(field.raw_data[0].replace(
                numbers.get_group_symbol(flask_babel.get_locale()), ''))
        except (ValueError, TypeError, InvalidOperation, AttributeError):
            raise validators.StopValidation(self.message)

        if 'e' in field.raw_data[0].lower():
            raise validators.StopValidation(self.message)
Exemple #16
0
 def __call__(self, form, field):
     if match := email_regex.match(field.data):
         hostname = match.group(1)
         try:
             hostname = hostname.encode("idna").decode("ascii")
         except UnicodeError:
             raise validators.StopValidation(self.message)
         parts = hostname.split(".")
         if len(parts) > 1 and not tld_part_regex.match(parts[-1]):
             raise validators.StopValidation(self.message)
Exemple #17
0
def validate_expires_at(form, field):
    """Validate that date is in the future."""
    if form.accept.data:
        if not field.data or datetime.utcnow().date() >= field.data:
            raise validators.StopValidation(_("Please provide a future date."))
        if not field.data or \
                datetime.utcnow().date() + timedelta(days=365) < field.data:
            raise validators.StopValidation(
                _("Please provide a date no more than 1 year into the future.")
            )
Exemple #18
0
 def validate_area(self, area):
     if area.data:
         lis = ['province', 'city', 'home']
         for h, i in zip(lis, area.data):
             if not isinstance(i, dict):
                 raise validators.StopValidation('地区输入不正确!')
             try:
                 self[h].data = i['code']
             except:
                 raise validators.StopValidation('地区输入不正确')
Exemple #19
0
 def __call__(self, form: "QuestionnaireForm", field: StringField) -> None:
     if match := email_regex.match(field.data):
         hostname = match.group(1)
         try:
             hostname = hostname.encode("idna").decode("ascii")
         except UnicodeError as exc:
             raise validators.StopValidation(self.message) from exc
         parts = hostname.split(".")
         if len(parts) > 1 and not tld_part_regex.match(parts[-1]):
             raise validators.StopValidation(self.message)
Exemple #20
0
    def validate_alias(self, field):
        reg_type = get_reg_type_from_alias(field.data)
        if not reg_type:
            raise validators.StopValidation(message=u'手机号或邮箱错误')

        if reg_type == ACCOUNT_REG_TYPE.EMAIL:
            if not errors.err_ok == validate_email(field.data):
                raise validators.StopValidation(message=u'邮箱错误')

        elif reg_type == ACCOUNT_REG_TYPE.MOBILE:
            if not errors.err_ok == validate_phone(field.data):
                return validators.StopValidation(message=u'手机号错误')
Exemple #21
0
    def __call__(self, form, field):
        if not form.data:
            raise validators.StopValidation(self.message)

        try:
            if hasattr(form, "day"):
                datetime.strptime(form.data, "%Y-%m-%d")
            elif hasattr(form, "month"):
                datetime.strptime(form.data, "%Y-%m")
            else:
                datetime.strptime(form.data, "%Y")
        except ValueError:
            raise validators.StopValidation(self.message)
Exemple #22
0
    def __call__(
        self,
        form: FlaskForm,
        field: Union[DecimalFieldWithSeparator, IntegerFieldWithSeparator],
    ) -> None:
        try:
            Decimal(field.raw_data[0].replace(
                numbers.get_group_symbol(flask_babel.get_locale()), ""))
        except (ValueError, TypeError, InvalidOperation,
                AttributeError) as exc:
            raise validators.StopValidation(self.message) from exc

        if "e" in field.raw_data[0].lower():
            raise validators.StopValidation(self.message)
    def UsernameOrEmailExists(self, form, field):
        pattern = re.compile(app.config['EMAIL_REGEX'])

        # If this is an email.
        if pattern.match(field.data):
            self.user = User.from_email(field.data)
            if not self.user:
                raise validators.StopValidation(
                    "We can't find a user with the email %s." % field.data)
        else:
            self.user = User.by_username(field.data)
            if not self.user:
                raise validators.StopValidation(
                    "We can't find a user with the name %s." % field.data)
Exemple #24
0
    def __call__(self, form: "QuestionnaireForm", field: StringField) -> None:
        if not form.data:
            raise validators.StopValidation(self.message)

        try:
            if hasattr(form, "day"):
                datetime.strptime(form.data,
                                  "%Y-%m-%d").replace(tzinfo=timezone.utc)
            elif hasattr(form, "month"):
                datetime.strptime(form.data,
                                  "%Y-%m").replace(tzinfo=timezone.utc)
            else:
                datetime.strptime(form.data, "%Y").replace(tzinfo=timezone.utc)
        except ValueError as exc:
            raise validators.StopValidation(self.message) from exc
Exemple #25
0
    def __call__(self, form, field):

        if not form.data or not re.match(r"\d{4}$", str(form.year.data)):
            raise validators.StopValidation(self.message)

        try:
            substrings = form.data.split("-")
            if len(substrings) == 3:
                datetime.strptime(form.data, "%Y-%m-%d")
            if len(substrings) == 2:
                datetime.strptime(form.data, "%Y-%m")
            if len(substrings) == 1:
                datetime.strptime(form.data, "%Y")
        except ValueError:
            raise validators.StopValidation(self.message)
Exemple #26
0
 def __call__(self, form, field):
     if (not field.raw_data
             or (len(field.raw_data[0])
                 and isinstance(field.raw_data[0][0], string_types)
                 and not self.string_check(field.raw_data[0][0]))):
         field.errors[:] = []
         raise validators.StopValidation()
Exemple #27
0
 def __call__(self, form, field):
     with db_session:
         name = self.attr_name
         if self.entity.select(
                 lambda o: getattr(o, name) == field.data).first():
             field.errors[:] = []
             raise validators.StopValidation(message=self.message)
Exemple #28
0
 def __call__(self, form, field):
     if field.data is None or isinstance(field.data, text_type) \
        and not field.data.strip():
         message = self.message or field.gettext(
             'This field is required. <No Value>')
         field.errors[:] = []
         raise validators.StopValidation(message)
Exemple #29
0
    def __call__(self, form, field):
        other_field = self.get_other_field(form)

        # if no values (for other_field) which make this field optional
        # are specified...
        if not self.optvals:
            # ... just make this field optional if the other is truthy
            if bool(other_field.data):
                super(OptionalIf, self).__call__(form, field)
        else:
            # if such values are specified, check for them
            no_optval_matched = True
            for v in self.optvals:
                if isinstance(other_field.data, list):
                    if v in other_field.data and len(other_field.data) == 1:
                        # must be the only option submitted - OK for
                        # radios and for checkboxes where a single
                        # checkbox, but no more, is required to make the
                        # field optional
                        no_optval_matched = False
                        self.__make_optional(form, field)
                        break
                if other_field.data == v:
                    no_optval_matched = False
                    self.__make_optional(form, field)
                    break

            if no_optval_matched:
                if not field.data:
                    raise validators.StopValidation('This field is required')
Exemple #30
0
 def __call__(self, form, field):
     try:
         datestr = '{}-{:02d}'.format(int(form.year.data or 0),
                                      int(form.month.data or 0))
         datetime.strptime(datestr, '%Y-%m')
     except ValueError:
         raise validators.StopValidation(self.message)