예제 #1
1
class SignupForm(FlaskForm):
    """The signup form"""
    email = StringField('Email Address', [
        validators.data_required(),
        validators.Length(min=6, max=35),
        validators.email(message="Invalid email address"),
        validators.regexp(
            r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
            flags=0,
            message="Invalid email address")
    ])
    username = StringField('Username', [
        validators.data_required(),
        validators.Length(min=3, max=25),
        validators.regexp(r"(^[a-zA-Z _.+-]+$)",
                          message="Only text characters allowed for username.")
    ])
    password = PasswordField('New Password', [
        validators.input_required(),
        validators.EqualTo('confirm', message='Passwords must match'),
        validators.length(
            min=8, message='Password needs to be atleast 8 characters long')
    ])
    confirm = PasswordField('Confirm Password', [validators.data_required()])
    submit = SubmitField("Submit")
예제 #2
0
파일: demo21.20.py 프로젝트: omitcn/Python
class MyForm(FlaskForm):
    name = TextField('姓名', [validators.Required('请输入姓名')])
    email = TextField(
        'Email',
        [validators.Required('请输入Email'),
         validators.email('请输入正确的Email地址')])
    ip = TextField('IP', [
        validators.Required('请输入IP地址'),
        validators.IPAddress(message='请输入正确的IP地址')
    ])
    password1 = PasswordField('密码', [validators.Required('请输入密码')])
    password2 = PasswordField('确认密码', [
        validators.Required('请确认密码'),
        validators.EqualTo('password1', '两次输入的密码不一致')
    ])

    value = TextField('电子邮件',
                      [validators.Email('Email格式不正确'),
                       validators.optional()])
    url = TextField(
        'Url', [validators.URL(message='Url格式不正确'),
                validators.optional()])

    regexpValue = TextField('正则表达式', [
        validators.Regexp('^[a-z]{3}-[1-9]{3}$', message='格式错误,正确格式:abc-123'),
        validators.Optional()
    ])
    submit = SubmitField('提交')
예제 #3
0
class CheckoutForm(FlaskForm):
    firstname = StringField("First Name", validators=[InputRequired()])
    lastname = StringField("Last name", validators=[InputRequired()])
    email = StringField("Email-ID", validators=[InputRequired(), email()])
    phone = StringField("Phone No.", validators=[InputRequired()])
    address = StringField("Delivery Address", validators=[InputRequired()])
    submit = SubmitField("Place Order")
class formulario(Form):
    nombre = StringField('Nombre: ', [
        validators.required('Es obligatorio'),
        validators.length(min=5, max=30, message='Nombre no valido!!')
    ])
    apellido = StringField('Apellidos: ', [
        validators.required('Es obligatorio'),
        validators.length(min=5, max=30, message='Nombre demasiado largo!!')
    ])
    direccion = TextField('Dirección: ', [
        validators.required('Dirección requerida!!'),
        validators.length(min=10, max=100, message='Dirección muy larga!!')
    ])
    localidad = TextField('Localidad: ', [
        validators.required('Localidad Requerida!!'),
        validators.length(min=10, max=100, message='Localidad muy larga!!')
    ])
    nacionalidad = TextField('Nacionalidad: ', [
        validators.required('Nacionalidad Requerida!!'),
        validators.length(min=10, max=100, message='Nacionalidad muy larga!!')

    ])
    email = EmailField('Email: ', [
        validators.required('Es Obligatorio'),
        validators.email('Ingrese su Email valido!')
    ])
    dni = TextField('DNI (00000000T): ', [
        validators.length(
            min=0, max=9, message='Se excede del limite permitido.')
    ])
    password = PasswordField('Contraseña: ', [
        validators.required('Campo requerido')
    ])
    # trampa honeypot
    honeypot = HiddenField('', [honeypot_len])
예제 #5
0
class updateAccount(FlaskForm):
    username = StringField('Username',
                           validators=[data_required(),
                                       length(min=2, max=20)])
    email = StringField('Email', validators=[data_required(), email()])
    picture = FileField('Update profile picture',
                        validators=[FileAllowed(['jpg', 'png', 'jpeg'])])
    submit = SubmitField('Update')

    def validate_username(self, username):

        if username.data != current_user.username:
            user = User.query.filter_by(username=username.data).first()
            if user:
                username.data = ''
                raise ValidationError(
                    'Username is already taken, Please use different one ')

    def validate_email(self, email):

        if email.data != current_user.email:
            emaill = User.query.filter_by(email=email.data).first()
            if emaill:
                email.data = ''
                raise ValidationError('Email already in Use')
예제 #6
0
class EmailScoresForm(BaseForm):
    subject = StringField('Subject', validators=[validators.required()])
    body = TextAreaField(
        'Body',
        validators=[validators.required()],
        description=
        "Is there anything the students need to know about the scores?",
        default=
        "An instructor has published scores. If you have questions, please contact the course staff"
    )
    reply_to = EmailField(
        'Reply To Address',
        default="*****@*****.**",
        description="What email should replies be sent to?",
        validators=[validators.required(),
                    validators.email()])
    dry_run = BooleanField(
        'Dry Run Mode',
        default=True,
        description=
        "Don't send emails to students; instead, send a few examples to your email."
    )
    kinds = MultiCheckboxField(
        'Scores Tags',
        choices=[(kind, kind.title()) for kind in SCORE_KINDS],
    )
예제 #7
0
class RealEstateForm(Form):
    def __repr__(self):
        return 'RealEstateForm'

    logo = FileField('')
    name = TextField('', [
        validators.Required(
            message=u'Debe ingresar un nombre de Inmobiliaria.')
    ])
    email = TextField('', [
        validators.email(message=u'Debe ingresar un correo válido.'),
        validators.Required(message=u'Debe ingresar un correo electrónico.')
    ],
                      default='')
    telephone_number = TextField('')
    telephone_number2 = TextField('')
    open_at = TextField('')

    def update_object(self, rs):
        rs.name = self.name.data
        rs.email = self.email.data
        rs.telephone_number = self.telephone_number.data
        rs.telephone_number2 = self.telephone_number2.data
        rs.open_at = self.open_at.data
        return rs
예제 #8
0
class LoginForm(BaseForm):
    email = TextField('Email',
                      validators=[validators.email(),
                                  validators.required()])
    password = PasswordField('Password', validators=[validators.required()])

    def validate(self):
        check_validate = super(LoginForm, self).validate()

        # if our field validators do not pass
        if not check_validate:
            return False

        # Does the user exist?
        user = User.query.filter_by(email=self.email.data).first()
        if not user:
            self.email.errors.append('Invalid email or password')
            return False

        # Do the passwords match
        if not user.check_password(self.password.data):
            self.email.errors.append('Invalid email or password')
            return False

        return True
예제 #9
0
class SupportForm(FlaskForm):
    email = StringField("Email Address",
                        validators=[
                            InputRequired(message='Please provide a value'),
                            email(message='Invalid email format'),
                            Length(min=3, max=30)
                        ])

    phone = StringField("Phone number",
                        validators=[
                            InputRequired(message='Please provide a value'),
                            Length(min=5, max=13)
                        ])

    question = TextAreaField(
        "Question",
        render_kw={'style': 'min-height: 180px;'},
        validators=[
            InputRequired(message='Please provide your question'),
            Length(min=5, max=400)
        ])

    submit = SubmitField(
        "Submit",
        render_kw={
            'style': 'margin-top: 10px; background-color: #dc3545; color:#fff'
        })
예제 #10
0
def test_valid_email_passes(email_address, dummy_form, dummy_field):
    """
    Valid email address should pass without raising
    """
    validator = email()
    dummy_field.data = email_address
    validator(dummy_form, dummy_field)
예제 #11
0
class SignupForm(BaseForm):
    email = TextField('Email',
                      validators=[validators.email(),
                                  validators.required()])
    password = PasswordField('Password',
                             validators=[
                                 validators.required(),
                                 validators.length(min=4),
                                 validators.EqualTo(
                                     'confirm', message='Passwords must match')
                             ])
    confirm = PasswordField('Confirm Password',
                            validators=[validators.required()])

    def validate(self):
        check_validate = super(SignupForm, self).validate()

        # if our field validators do not pass
        if not check_validate:
            return False

        # Does the user exist already? Must return false,
        # otherwise we'll allow anyone to sign in
        user = User.lookup(self.email.data)
        if user:
            self.email.errors.append('That email already has an account')
            return False

        return True
예제 #12
0
파일: forms.py 프로젝트: eliefly/refer
class CommentForm(Form):
    author = TextField('name', validators=[Required()])
    email = TextField('email (not visible to others)',
                      validators=[Required(), validators.email()])
    comment = TextAreaField('comment',
                            validators=[Required(),
                                        validators.Length(2, 500)])
예제 #13
0
파일: forms.py 프로젝트: dickiebush/Rescu
class LoginForm(Form):
    email = StringField(
        'email', validators=[validators.DataRequired(),
                             validators.email()])
    password = PasswordField('password',
                             validators=[validators.DataRequired()])
    remember_me = BooleanField('remember_me', default=True)
예제 #14
0
파일: form.py 프로젝트: g389158097/bookc
class ChangeUserForm(FlaskForm):
    username = StringField(label='用户昵称',
                           validators=[
                               DataRequired("昵称必填"),
                               Length(min=6, max=20, message="用户名必须介于6-20个字符")
                           ],
                           render_kw={"placeholder": "用户名必须介于6-20个字符"})
    password = StringField(label="用户密码",
                           validators=[DataRequired("密码必填!")],
                           render_kw={
                               "placeholder": '密码必须大于6个字符',
                           })
    email = StringField(
        '邮箱',
        validators=[email(message="邮箱格式不正确!")],
        render_kw={"placeholder": "E-mail: [email protected]"})

    realname = StringField(label='用户姓名',
                           validators=[
                               DataRequired("姓名必填"),
                               Length(min=2, max=5, message="请输入真实姓名")
                           ],
                           render_kw={"placeholder": "请输入真实姓名"})
    gender = RadioField(label='性别',
                        choices=[('m', '男'), ('f', '女')],
                        validators=[DataRequired()])
    age = IntegerField(
        label='年龄',
        validators=[DataRequired("年龄必填"),
                    NumberRange(min=16, max=100)],
        render_kw={"placeholder": "请输入真实年龄"})
    submit = SubmitField(label='确认修改')
예제 #15
0
class SigninForm(FlaskForm):
    username = StringField('username',
                           render_kw={
                               'class': 'form-control',
                               'placeholder': 'Username'
                           },
                           validators=[DataRequired(),
                                       Length(1, 20)])
    mail = StringField('mail',
                       render_kw={
                           'class': 'form-control',
                           'placeholder': 'Email'
                       },
                       validators=[DataRequired(), email()])  # 邮箱输入框并验证
    password = PasswordField('password',
                             render_kw={
                                 'class': 'form-control',
                                 'placeholder': 'Password'
                             },
                             validators={DataRequired(),
                                         Length(1, 20)})
    re_password = PasswordField('password',
                                render_kw={
                                    'class': 'form-control',
                                    'placeholder': 'Repassword'
                                },
                                validators={DataRequired(),
                                            Length(1, 20)})  # 验证密码
    submit = SubmitField(render_kw={
        'class': 'form-control btn-info',
        'value': '注册'
    })
예제 #16
0
class RegistrationForm(FlaskForm):

    user_first_name = StringField(
        'first name',
        validators=[
            InputRequired(),
            Length(min=2,
                   max=20,
                   message='you name must have letters in range of 2 upto 20 ')
        ])
    user_second_name = StringField(
        'second name',
        validators=[
            InputRequired(),
            Length(min=2,
                   max=20,
                   message='you name must have letters in range of 2 upto 20 ')
        ])
    user_middle_name = StringField('middle name')
    user_email = StringField('email', validators=[InputRequired(), email()])
    user_password = PasswordField('password', validators=[InputRequired()])
    user_confirm_password = PasswordField(
        'user_confirm password',
        validators=[
            InputRequired(),
            EqualTo('user_password', message='you entered diffirent password')
        ])
    submit = SubmitField('SIGN UP')
예제 #17
0
class LoginForm(form.Form):
    login = fields.TextField(
        validators=[validators.required(),
                    validators.email()],
        render_kw={"placeholder": "*****@*****.**"})
    password = fields.PasswordField(validators=[validators.required()],
                                    render_kw={"placeholder": "xyzzy"})

    def validate_login(self, field):
        """
        validate login
        :param field:
        :return:
        """
        user = self.get_user()

        if user is None:
            raise validators.ValidationError('User does not exist.')

        if user.password != generate_password_hash(self.password.data,
                                                   user.salt):
            raise validators.ValidationError('Credentials incorrect.')

        if not user.is_admin and not user.is_super_admin:
            raise validators.ValidationError(
                'Access Forbidden. Admin Rights Required')

    def get_user(self):
        return User.query.filter_by(email=self.login.data).first()
예제 #18
0
class LoginForm(FlaskForm):
    def valid_user(form, field):
        user = User.query.filter_by(email=field.data).first()

        if not user:
            raise ValidationError('Incorrect email address.')

        if not user.email_confirmed:
            flash('Please confirm you email first.')
            raise ValidationError('unconfirmed_email')

    def valid_pw(form, field):
        user = User.query.filter_by(email=form.email.data).first()

        if not user:
            pass

        else:
            validated_pw = bcrypt.check_password_hash(user.pw_hash,
                                                      form.password.data)

            if not validated_pw:
                raise ValidationError('Incorrect password.')

    email = StringField('Email', [
        email(),
        DataRequired(message='This field is required.'),
        Length(max=100), valid_user
    ])

    password = PasswordField('Password', [
        DataRequired(message='This field is required.'),
        Length(min=8, max=128), valid_pw
    ])
예제 #19
0
class InviteMemberForm(BaseForm):
    email = StringField('Email',
                        validators=[validators.email(),
                                    validators.required()])
    role = SelectField('Role',
                       default='team member',
                       choices=[(r, r.title()) for r in TEAM_MEMBER_ROLES])
예제 #20
0
class CreateAccountForm(FlaskForm):
    def unique_user(form, field):
        existing_user = User.query.filter_by(email=field.data).first()

        if existing_user:
            raise ValidationError('That email address is taken.')

    username = StringField(
        'Username',
        [DataRequired(message='This field is required.'),
         Length(max=20)])

    email = StringField('Email', [
        DataRequired(message='This field is required.'),
        email(),
        Length(max=100), unique_user
    ])

    password = PasswordField('Password', [
        DataRequired(message='This field is required.'),
        Length(min=8, max=128)
    ])

    confirm_password = PasswordField('Confirm Password', [
        DataRequired(message='This field is required.'),
        Length(min=8, max=128),
        EqualTo('password', message='Passwords must match.')
    ])
예제 #21
0
class HelpDeskForm(Form):
    def __repr__(self):
        return 'HelpDeskForm'

    sender_name = TextField(
        '', [validators.Required(message=u'Debe ingresar un nombre.')])
    sender_email = TextField('', [
        validators.email(message=u'Debe ingresar un correo válido.'),
        validators.Required(message=u'Debe ingresar un correo.')
    ],
                             default='')
    sender_telephone = TextField('')
    sender_subject = TextField(
        '', [validators.Required(message=u'Debe ingresar un Asunto.')])
    sender_comment = TextAreaField(
        '', [validators.Required(message=u'Debe ingresar un Comentario.')],
        default='')

    def update_object(self, help_desk):
        help_desk.sender_name = self.sender_name.data
        help_desk.sender_email = self.sender_email.data
        help_desk.sender_telephone = self.sender_telephone.data
        help_desk.sender_subject = self.sender_subject.data
        help_desk.sender_comment = self.sender_comment.data

        return help_desk
예제 #22
0
class Reset_Confirm_Email_Form(FlaskForm):
    def unique_user(form, field):
        existing_user = User.query.filter_by(email=field.data).first()

        if existing_user:
            raise ValidationError('That email address is taken.')

    def valid_pw(form, field):
        user = User.query.filter_by(email=form.old_email.data).first()

        validated_pw = bcrypt.check_password_hash(user.pw_hash,
                                                  form.password.data)

        if not validated_pw:
            raise ValidationError('Incorrect password.')

    email = StringField('New Email Address', [
        email(),
        DataRequired(message='This field is required.'), unique_user,
        Length(max=100)
    ])

    old_email = HiddenField("old_email")

    password = PasswordField('Password', [
        DataRequired(message='This field is required.'),
        Length(min=8, max=128), valid_pw
    ])
예제 #23
0
class ReSetEmailForm(FormBase):
    email = StringField(validators=[
        email(message='邮箱格式不正确'),
        InputRequired(message='邮箱输入不能为空')
    ])
    captche = StringField(
        validators=[Length(min=6, max=6, message='请输入正确验证码长度')])

    def validate_email(self, field):
        print(field)
        email = field.data
        print(email)
        print(g.u.email)
        if email == g.u.email:
            raise ValidationError('修改邮箱和当前邮箱重复!')
        is_exis = User.query.filter(User.email == email).count()
        if is_exis:
            print(is_exis)
            raise ValidationError('修改邮箱已经存在!')

    def validate_captche(self, field):
        captche = field.data
        try:
            redis_captche = redis.get(self.email.data)
        except Exception as e:
            raise ValidationError(str(e))
        if not redis_captche or redis_captche.decode(
                'utf-8').lower() != captche.lower():
            raise ValidationError('验证码输入不正确!')
예제 #24
0
class RegisterForm(Form):
    honeypot = HiddenField("", [length_honeypot])

    username = StringField('Username', [
        validators.length(
            min=4, max=50, message='El usuario se encuentra fuera de rango'),
        codi_validator
    ])
    email = EmailField('Correo electronico', [
        validators.length(min=6, max=100),
        validators.Required(message='El email es requerido.'),
        validators.email(message='Ingrese un email valido')
    ])
    password = PasswordField('Password', [
        validators.Required('La contraseña es requerida'),
        validators.EqualTo('confirm_password',
                           message='La contraseña no coincide')
    ])
    confirm_password = PasswordField('Confirm password')
    accept = BooleanField('', [validators.DataRequired()])

    def validate_username(self, username):
        if User.get_by_username(username.data):
            raise validators.ValidationError(
                'El usuario ya se encuentra en uso')

    def validate_email(self, email):
        if User.get_by_email(email.data):
            raise validators.ValidationError('El email ya se encuentra en uso')
예제 #25
0
class ExtensionForm(SubmissionTimeForm):
    assignment_id = SelectField('Assignment',
                                coerce=int,
                                validators=[validators.required()])
    expires = DateTimeField('Extension Expiry',
                            validators=[validators.required()])
    email = EmailField('Student Email',
                       validators=[validators.required(),
                                   validators.email()])
    reason = StringField('Justification',
                         description="Why are you granting this extension?",
                         validators=[validators.optional()])

    def __init__(self, obj=None, **kwargs):
        self.obj = obj
        super(ExtensionForm, self).__init__(obj=obj, **kwargs)

    def validate(self):
        check_validate = super(ExtensionForm, self).validate()
        # if our validators do not pass
        if not check_validate:
            return False
        user = User.lookup(self.email.data)
        if not user:
            message = "{} does not have an OK account".format(self.email.data)
            self.email.errors.append(message)
            return False
        return check_validate
예제 #26
0
class RegistrationForm(FlaskForm):
    username = StringField('Username',
                           validators=[
                               validators.input_required(),
                           ])
    email = StringField('Email',
                        validators=[
                            validators.input_required(),
                            validators.email(),
                        ])
    password = PasswordField('Password',
                             validators=[
                                 validators.input_required(),
                                 validators.length(min=8, max=30)
                             ])
    password2 = PasswordField('Repeat Password',
                              validators=[
                                  validators.input_required(),
                                  validators.equal_to('password'),
                              ])

    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('This username is already in use.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('This email is already in use.')
예제 #27
0
class ParticipantForm(Form):
    id = IntegerField(label="ID")
    email = StringField(label="Email",
                        validators=[validators.email(),
                                    validators.required()])
    name = StringField(label="Name", validators=[validators.required()])
    affiliation = StringField(label="Affiliation",
                              validators=[validators.required()])
    uniqueURL = StringField(label="URL", validators=[validators.required()])
    country_id = IntegerField(label="country_id",
                              validators=[validators.required()])

    def setScope(self, scope):
        if scope == "update":
            self.id.validators = [validators.required()]
            # self.oldPassword.validators = [requiredIf("password")]
            # print(type(self.userid.validators[0]).__name__)

    #   if scope == "add":
    #     self.id.validators.append(validators.required())

    def add(self):
        ret = {}
        try:
            pass
        except Exception as e:
            pass
        finally:
            pass

    def validate(self):
        status = True
        rv = Form.validate(self)
        if not rv:
            status = False
예제 #28
0
class RegistrationForm(Form):
    username = StringField('Username', [validators.Length(min=3, max=50)])
    password = PasswordField('Password', [validators.InputRequired()])
    email = StringField(
        'Email address (please use a real one, we\'ll send a confirmation email)',
        [validators.Length(min=6, max=100), validators.email()])

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = None

    def validate(self):
        if not super().validate():
            return False

        if User.query.filter_by(username=self.username.data).first():
            self.username.errors.append('Username already taken')
            return False
        if User.query.filter_by(email=self.email.data).first():
            self.email.errors.append('Email already in use')
            return False

        self.user = User.with_password(
            username=self.username.data,
            password=self.password.data,
            email=self.email.data)
        return True
예제 #29
0
파일: forms.py 프로젝트: z00107647/polaris
class LoginForm(FlaskForm):
    email = StringField('邮箱',
                        validators=[InputRequired(),
                                    email(message='邮箱格式错误')])
    password = PasswordField('密码', validators=[InputRequired()])
    remember_me = BooleanField('记住我')
    submit = SubmitField('登录')
예제 #30
0
파일: views.py 프로젝트: spot-summers/burp
class UserView(ModelView):
    """
    ModelView override of Flask Admin for Users.
    """
    # CSRF protection
    form_base_class = Form

    # Ensure user is authenticated
    def is_accessible(self):
        return login.current_user.is_authenticated()

    # Column tweaks
    column_list = ('email', 'assessments')
    column_labels = dict(email='Email Address', assessments='Assessments')

    # Form tweaks and validations
    form_args = dict(email=dict(
        description=
        'Enter email address to recieve notifications when captures are recieved',
        validators=[validators.required(),
                    validators.email()]),
                     assessments=dict(
                         description=
                         'Subscribe to assessments to recieve notifications',
                         validators=[validators.required()]))

    def __init__(self, session, **kwargs):
        super(UserView, self).__init__(User, session, **kwargs)
예제 #31
0
    def test_lazy_proxy(self):
        """Tests that the validators support lazy translation strings for messages."""

        class ReallyLazyProxy(object):
            def __unicode__(self):
                raise Exception('Translator function called during form declaration: it should be called at response time.')
            __str__ = __unicode__

        message = ReallyLazyProxy()
        self.assertRaises(Exception, str, message)
        self.assertRaises(Exception, text_type, message)
        self.assertTrue(equal_to('fieldname', message=message))
        self.assertTrue(length(min=1, message=message))
        self.assertTrue(NumberRange(1, 5, message=message))
        self.assertTrue(required(message=message))
        self.assertTrue(regexp('.+', message=message))
        self.assertTrue(email(message=message))
        self.assertTrue(ip_address(message=message))
        self.assertTrue(url(message=message))
예제 #32
0
 def test_email(self):
     self.assertEqual(email()(self.form, DummyField('*****@*****.**')), None)
     self.assertEqual(email()(self.form, DummyField('*****@*****.**')), None)
     self.assertEqual(email()(self.form, DummyField('*****@*****.**')), None)
     self.assertEqual(email()(self.form, DummyField('*****@*****.**')), None)
     self.assertRaises(ValidationError, email(), self.form, DummyField(None))
     self.assertRaises(ValidationError, email(), self.form, DummyField(''))
     self.assertRaises(ValidationError, email(), self.form, DummyField('  '))
     self.assertRaises(ValidationError, email(), self.form, DummyField('foo'))
     self.assertRaises(ValidationError, email(), self.form, DummyField('bar.dk'))
     self.assertRaises(ValidationError, email(), self.form, DummyField('foo@'))
     self.assertRaises(ValidationError, email(), self.form, DummyField('@bar.dk'))
     self.assertRaises(ValidationError, email(), self.form, DummyField('foo@bar'))
     self.assertRaises(ValidationError, email(), self.form, DummyField('[email protected]'))
     self.assertRaises(ValidationError, email(), self.form, DummyField('*****@*****.**'))
예제 #33
0
 def conv_EmailField(self, model, field, kwargs):
     kwargs["validators"].append(validators.email())
     return f.StringField(**kwargs)
예제 #34
0
    BooleanField,
    PasswordField,
    SelectField,
    TextField,
    validators,
)

loginField = TextField('Login', [validators.Length(min=4, max=10)])

passwordField = PasswordField('Password', [validators.Length(min=6, max=15)])

editPasswordField = PasswordField('Password', [validators.Optional(),
                                              validators.Length(min=6, max=15)])

confirmField = PasswordField('Confrim', [validators.EqualTo(
    'password', message='Passwords must match')])

firstNameField = TextField('First Name', [validators.Length(min=2, max=25)])

lastNameField = TextField('Last_name', [validators.Length(min=2, max=25)])

phoneField = TextField('Phone', [])

emailField = TextField('Email', [validators.email()])

securedField = BooleanField(u'Secured', [])

basicField = BooleanField(u'Basic', [])

groupField = SelectField('', choices=[(u'basic', u'Basic'), (u'secured', u'Secured')])
예제 #35
0
 def test_email(self):
     self.assertEqual(email()(self.form, DummyField("*****@*****.**")), None)
     self.assertEqual(email()(self.form, DummyField("*****@*****.**")), None)
     self.assertEqual(email()(self.form, DummyField("*****@*****.**")), None)
     self.assertEqual(email()(self.form, DummyField("*****@*****.**")), None)
     self.assertRaises(ValidationError, email(), self.form, DummyField(None))
     self.assertRaises(ValidationError, email(), self.form, DummyField(""))
     self.assertRaises(ValidationError, email(), self.form, DummyField("  "))
     self.assertRaises(ValidationError, email(), self.form, DummyField("foo"))
     self.assertRaises(ValidationError, email(), self.form, DummyField("bar.dk"))
     self.assertRaises(ValidationError, email(), self.form, DummyField("foo@"))
     self.assertRaises(ValidationError, email(), self.form, DummyField("@bar.dk"))
     self.assertRaises(ValidationError, email(), self.form, DummyField("foo@bar"))
     self.assertRaises(ValidationError, email(), self.form, DummyField("[email protected]"))
     self.assertRaises(ValidationError, email(), self.form, DummyField("*****@*****.**"))
예제 #36
0
 def Email(cls, message=None):
     ''' Validates an email address '''
     return validators.email(message)
예제 #37
0
파일: db.py 프로젝트: ProjectMonsoon/app
def convert_EmailProperty(model, prop, kwargs):
    """Returns a form field for a ``db.EmailProperty``."""
    kwargs['validators'].append(validators.email())
    return get_TextField(kwargs)
예제 #38
0
파일: orm.py 프로젝트: sherrycherish/qiubai
 def conv_EmailField(self, model, field, kwargs):
     kwargs['validators'].append(validators.email())
     return f.TextField(**kwargs)
예제 #39
0
    def input_field(self, field_data, display_name, row_name, control_id, control_type, value=None):
        kwargs = {}
        validators = []
        if value is not None:
            kwargs['default'] = value

        # no validators or classes attached to hidden fields, as it could cause issues
        # e.g. an empty hidden required field
        if field_data.FieldRole.visible != constants.VISIBLE:
            return HiddenField(field_data.FieldRole.display_name, **kwargs)

        if field_data.Field.description != "":
            kwargs['title'] = field_data.Field.description

        if field_data.FieldRole.required == constants.REQUIRED:
            validators.append(DataRequired())
        else:
            validators.append(Optional())

        if field_data.Field.length is not None and field_data.Field.data_type_id == constants.STRING:
            validators.append(Length(0, field_data.Field.length))

        if "email" in field_data.Field.display_name:
            validators.append(email())

        kwargs['validators'] = validators

        if field_data.Field.field_class is not None:
            kwargs['iggybase_class'] = control_type + ' ' + field_data.Field.field_class
        else:
            kwargs['iggybase_class'] = control_type

        if ((field_data.FieldRole.permission_id == constants.DEFAULTED and row_name != 'new') or
                (field_data.FieldRole.permission_id == constants.IMMUTABLE and row_name == 'new') or
                (field_data.FieldRole.permission_id == constants.READ_WRITE)):
            kwargs['readonly'] = False
        else:
            kwargs['readonly'] = True

        if field_data.Field.select_list_id is not None:
            choices = self.organization_access_control.get_select_list(field_data.Field.select_list_id)

            if kwargs['readonly']:
                value = [item for item in choices if item[0] == value]

                if len(value) > 0:
                    kwargs['default'] = value[0][1]

                return IggybaseStringField(display_name, **kwargs)
            else:
                if value is not None:
                    kwargs['default'] = value

                kwargs['coerce'] = int
                kwargs['choices'] = choices

                return IggybaseSelectField(display_name, **kwargs)
        elif field_data.is_foreign_key:
            long_text = self.role_access_control.has_access("TableObject", {'name': 'long_text'})

            if long_text.id == field_data.FK_TableObject.id:
                if value is not None:
                    lt_row = self.organization_access_control.get_long_text(value)
                    kwargs['default'] = lt_row.long_text
                    self.classattr['long_text_' + control_id] = HiddenField('long_text_' + control_id, default=value)
                else:
                    self.classattr['long_text_' + control_id] = HiddenField('long_text_' + control_id)

                return IggybaseTextAreaField(display_name, **kwargs)
            else:
                if field_data.name not in self.dropdowns:
                    self.dropdowns[field_data.name] = self.organization_access_control.\
                        get_foreign_key_data(field_data.FK_TableObject, field_data.FK_Field)

                choices = self.dropdowns[field_data.name]

                if field_data.Field.drop_down_list_limit:
                    drop_down_limit = field_data.Field.drop_down_list_limit
                else:
                    drop_down_limit = 25

                if len(choices) > drop_down_limit:
                    kwargs['iggybase_class'] = control_type

                    if value is None:
                        self.classattr['id_' + control_id] = HiddenField('id_' + control_id)
                    else:
                        value = [item for item in choices if item[0] == value]

                        if len(value) > 0:
                            kwargs['default'] = value[0][1]

                            self.classattr['id_' + control_id] = HiddenField('id_' + control_id, default=value[0][0])
                        else:
                            self.classattr['id_' + control_id] = HiddenField('id_' + control_id)

                    return IggybaseLookUpField(display_name, **kwargs)
                elif kwargs['readonly']:
                    value = [item for item in choices if item[0] == value]

                    if len(value) > 0:
                        kwargs['default'] = value[0][1]

                    if value is not None:
                        kwargs['default'] = value

                    return IggybaseStringField(display_name, **kwargs)
                else:
                    kwargs['coerce'] = int
                    kwargs['choices'] = choices

                    if value is not None:
                        kwargs['default'] = value

                    return IggybaseSelectField(display_name, **kwargs)
        elif field_data.Field.data_type_id == constants.INTEGER:
            return IggybaseIntegerField(display_name, **kwargs)
        elif field_data.Field.data_type_id == constants.FLOAT:
            return IggybaseFloatField(display_name, **kwargs)
        elif field_data.Field.data_type_id == constants.BOOLEAN:
            self.classattr['bool_' + control_id]=HiddenField('bool_' + control_id, default=value)
            return IggybaseBooleanField(display_name, **kwargs)
        elif field_data.Field.data_type_id == constants.DATE:
            return IggybaseDateField(display_name, **kwargs)
        elif field_data.Field.data_type_id == constants.PASSWORD:
            return IggybasePasswordField(display_name, **kwargs)
        elif field_data.Field.data_type_id == constants.FILE:
            self.classattr['files_' + control_id] = HiddenField('files_' + control_id, default=value)
            return IggybaseFileField(display_name, **kwargs)
        elif field_data.Field.data_type_id == constants.TEXT_AREA:
            return IggybaseTextAreaField(display_name, **kwargs)
        else:
            return IggybaseStringField(display_name, **kwargs)