Ejemplo n.º 1
0
class MediaContactsForm(FlaskForm):
    Link1 = StringField('Instagram',
                        validators=[
                            DataRequired(),
                            url(message="Turi būti nurodoma nuoroda.")
                        ])
    Link2 = StringField('Facebook',
                        validators=[
                            DataRequired(),
                            url(message="Turi būti nurodoma nuoroda.")
                        ])
    Link3 = StringField('YouTube',
                        validators=[
                            DataRequired(),
                            url(message="Turi būti nurodoma nuoroda.")
                        ])
    Link4 = StringField('Global "iEARN"',
                        validators=[
                            DataRequired(),
                            url(message="Turi būti nurodoma nuoroda.")
                        ])

    contact1 = StringField('Instagram', validators=[DataRequired()])
    contact2 = StringField('YouTube', validators=[DataRequired()])
    contact3 = StringField('Facebook', validators=[DataRequired()])
    contact4 = StringField('Global "iEARN"', validators=[DataRequired()])

    submit = SubmitField('Išsaugoti')
Ejemplo n.º 2
0
class NewCourseForm(BaseForm):
    offering = StringField('Offering (e.g. cal/cs61a/sp16, cal/cs168/fa16, etc)',
                           validators=[validators.required()])
    institution = StringField('School (e.g. UC Berkeley)',
                           validators=[validators.optional()])
    display_name = StringField('Course Name (e.g CS61A, CS168, etc)',
                           validators=[validators.required()])
    website = StringField('Course Website',
                           validators=[validators.optional(), validators.url()])
    active = BooleanField('Activate Course', default=True)
    timezone = SelectField('Course Timezone', choices=[(t, t) for t in pytz.common_timezones],
                           default=TIMEZONE)
    autograder_url = StringField('Autograder Endpoint (Optional)',
                           validators=[validators.optional(), validators.url()])

    def validate(self):
        # if our validators do not pass
        if not super(NewCourseForm, self).validate():
            return False

        # Ensure the name has the right format:
        if not utils.is_valid_endpoint(self.offering.data, COURSE_ENDPOINT_FORMAT):
            self.offering.errors.append(('The name should look like univ/course101/semYY where "sem" is one of (fa, su, sp, au, wi)'))
            return False

        course = Course.query.filter_by(offering=self.offering.data).first()
        if course:
            self.offering.errors.append('That offering already exists.')
            return False
        return True
Ejemplo n.º 3
0
class New_Material_Form(FlaskForm):
    series = QuerySelectField("Series",
                              query_factory=lambda: Series.query.all(),
                              validators=[DataRequired()])
    note_url = URLField("Note URL", validators=[url()])
    slides_url = URLField("Slides URL", validators=[url()])

    submit = SubmitField("New")
Ejemplo n.º 4
0
class CourseUpdateForm(BaseForm):
    institution = StringField('School (e.g. UC Berkeley)',
                              validators=[validators.optional()])
    display_name = StringField('Course Name (e.g CS61A)',
                               validators=[validators.required()])
    website = StringField('Course Website',
                          validators=[validators.optional(), validators.url()])
    active = BooleanField('Activate Course', default=True)
    timezone = SelectField('Course Timezone', choices=[(t, t) for t in pytz.common_timezones])
    autograder_url = StringField('Autograder Endpoint (Optional)',
                           validators=[validators.optional(), validators.url()])
Ejemplo n.º 5
0
def test_lazy_proxy_fixture(really_lazy_proxy):
    """
    Tests that the validators support lazy translation strings for messages.
    """
    equal_to("fieldname", message=really_lazy_proxy)
    length(min=1, message=really_lazy_proxy)
    NumberRange(1, 5, message=really_lazy_proxy)
    data_required(message=really_lazy_proxy)
    regexp(".+", message=really_lazy_proxy)
    email(message=really_lazy_proxy)
    ip_address(message=really_lazy_proxy)
    url(message=really_lazy_proxy)
Ejemplo n.º 6
0
class Template(FlaskForm):
    Sitename = StringField("sitename", validators=[DataRequired()])
    Logo = FileField("Logo")
    Sitedesc = StringField("sitedesc")
    Sitegitloc = StringField(
        "sitegitloc",
        validators=[DataRequired(message="不允许为空"),
                    url(message="请按url的格式输入")])
    Sitebeian0 = StringField("sitebeian0")
    Sitebeian1 = StringField("sitebeian1")
    Siteloc = StringField("siteloc", validators=[url(message="请按url的格式输入")])
    Submit = SubmitField("submit_button")
Ejemplo n.º 7
0
class BookmarkForm(Form):
    url = URLField("url", validators=[DataRequired(), url()])
    description = StringField("description")

    # overwrite the validate() method of the form class (https://wtforms.readthedocs.io/en/stable/forms.html_)
    # This method is called when we call validate_on_submit() in VF
    def validate(self):
        # Run checks to see how url starts: IF the url does NOT start with http or https, then we add it automatically
        # Ie, if user doesn't enter http or https, we will add it for them BUT they must include the top-level domain  bc that's something the url validtora checks for
        if not self.url.data.startswith("http://") or self.url.data.startswith(
            "https://"
        ):
            self.url.data = "http://" + self.url.data

        # call the validate method on the parent class. This checks all other validtors against the data. If there's an error it retursn False
        if not Form.validate(self):
            return False

        # check if user has entered a description
        # IF not, I set the description to the url, that way the descriotion is NEVER empty
        if not self.description.data:
            self.description.data = self.url.data

        # imp to do this b/c validate() MUST return a bool
        return True
Ejemplo n.º 8
0
class UrlForm(Form):
    url = URLField(validators=[
        validators.url(),
        validators.Regexp(
            author_re,
            message='Must be like: http://explorer.silawet.com/author/...')
    ])
Ejemplo n.º 9
0
class BookmarkForm(Form):
    # customized validation function
    def validate_len(form, field):
        if len(field.data) > 15 or len(field.data) < 1:
            raise ValidationError('The length of description should be [1,15]')

    # using html5 url field
    url = URLField('New URL: ', validators=[DataRequired(), url()])
    description = StringField('Description: ', [validate_len])

    # customized the validation function
    # override the validate function
    # this will be called when validate_on_submit
    def validate(self):

        if not self.url.data.startswith("http://") or \
            self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data

        # original validation check
        if not Form.validate(self):
            return False

        # make description not empty
        if not self.description.data:
            self.description.data = self.url.data

        return True
Ejemplo n.º 10
0
class EditUserForm(FlaskForm):

    username = StringField("Username", validators=[InputRequired()])

    image_url = StringField("Profile Image URL", validators=[url()])

    password = PasswordField("Password", validators=[InputRequired()])
Ejemplo n.º 11
0
class UpdateProjectForm(FlaskForm):
    title = StringField(
        lazy_gettext('Tytuł'),
        validators=[
            DataRequired(message=lazy_gettext('To pole jest wymagane.')),
            Length(max=50,
                   message=lazy_gettext(
                       'Tytuł może się składać z maksymalnie 50 znaków.'))
        ])
    file = FileField(
        lazy_gettext('Projekt'),
        validators=[
            FileAllowed(['jpg', 'png', 'pdf'],
                        message=lazy_gettext(
                            'Plik musi mieć rozszerzenie jpg, png lub pdf.'))
        ])
    description = TextAreaField(
        lazy_gettext('Opis projektu'),
        validators=[
            DataRequired(message=lazy_gettext('To pole jest wymagane')),
            Length(max=1000,
                   message=lazy_gettext(
                       'Opis może się składać z maksymalnie 1000 znaków.'))
        ])
    url = URLField(lazy_gettext('Link do dodatkowych materiałów (opcjonalne)'),
                   validators=[
                       optional(),
                       url(message=lazy_gettext('Nieprawidłowy adres URL'))
                   ])
    submit = SubmitField(lazy_gettext('Edytuj'))
Ejemplo n.º 12
0
class BookmarkForm(Form):
    url = URLField('Enter your url:', validators=[DataRequired(), url()])
    description = StringField('Enter Description:')
    tags = StringField(
        'Tags',
        validators=[
            Regexp(r'^[a-zA-Z0-9, ]*$',
                   message='Tags can only contain letters and numbers')
        ])
    submit = SubmitField('Save')

    def validate(self):
        if not self.url.data.startswith("http://") or\
            self.url.data.startswith("https://"):
            self.url.data = "" + self.url.data

        if not Form.validate(self):
            return False
        if not self.description.data:
            self.description.data = self.url.data

        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)

        return True
Ejemplo n.º 13
0
class BadgeForm(FlaskForm):
    fullname = StringField(
        "Full Name",
        description="Your name that should be visible on the badge",
        validators=[DataRequired()],
    )
    avatar_url = URLField(
        "Avatar URL",
        description=
        "A link to the image that you want as your photo on the badge. The image ideally should be of 1:1 aspect ratio.",
        validators=[url()],
    )
    twitter_id = StringField("Twitter ID", description="Your Twitter ID")
    username = StringField(
        "Username",
        description=
        "By default, your username is a random ID. If you want a custom name in your badge URL, please put in here. Only lower case alphabets and hyphen '-' are allowed in this field. Please note that the usernames are First Come First Serve.",
        validators=[username_check],
    )
    about = StringField(
        "About",
        description="Write something unique about you",
        validators=[
            Length(max=80,
                   message="About section needs to be less than 80 characters")
        ],
    )
    submit = SubmitField("Save")
Ejemplo n.º 14
0
class BookmarkForm(FlaskForm):
    # for every input in the form, added a class attribute
    # Each of these attribute are then __Field instances. They represent the actual fields
    # validator objects are passed to validate
    # validate_on_submit() triggers these validators
    # the one below would trigger html5 url check
    # url = URLField('url', validators=[DataRequired(), url()])

    url = StringField('The URL for your bookmark', validators=[DataRequired(), url()])
    description = StringField('Add an optional description')

    # Overriding the original validate method inside FlaskForm
    def validate(self):
        if not self.url.data.startswith("http://") or \
                self.url.data.startswith("https://"):

            self.url.data = "http://"+self.url.data

        # call the original validate method in FlaskForm after modifying data
        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        return True
Ejemplo n.º 15
0
class BookmarkForm(FlaskForm):
    # url = URLField("url", validators=[DataRequired(), url()])
    # description = StringField('description')
    # user = StringField('user')

    url = URLField("Enter your bookmark here: ", validators=[DataRequired(), url()])
    description = StringField('Enter URL description(optional) here: ', validators=[Length(5, 100)])
    user = StringField('Enter your username here: ')
    tags = StringField("Tags", validators=[Regexp(r"[a-zA-Z0-9, ]*$",
                                            message="Tags can contain only number and letters(comma separated)")])

    def validate(self):
        if not self.url.data.startswith((r"http://", r"https://")):
            self.url.data = "".join(["https://",self.url.data])

        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        if not self.user.data:
            self.user.data = current_user.username

        # filter out the tags from the system
        stripped = set(filter(None, [t.strip() for t in self.tags.data.split(",")]))
        self.tags.data=",".join(sorted(stripped))

        return True
Ejemplo n.º 16
0
class RegisterForm(Form):
    username = StringField('Username: '******'^[A-Z,a-z0-9_]{3,}$')
                           ])
    name = StringField('Full name: ',
                       validators=[DataRequired(),
                                   Length(4, 65)])
    email = StringField('Email', validators=[DataRequired(), Email()])
    picture = URLField('URL for your photo: ',
                       validators=[DataRequired(), url()])
    password = PasswordField(
        'Password: '******'confirmPassword')])
    confirmPassword = PasswordField('Confirm Password',
                                    validators=[DataRequired()])
    submit = SubmitField('Log In')

    def validate_email(self, email_field):
        if User.query.filter_by(email=email_field.data).first():
            raise ValidationError(
                'An account with this email has already been created.')

    def validate_user(self, name_field):
        if User.query.filter_by(name=name_field.data).first():
            raise ValidationError('This username is taken')
Ejemplo n.º 17
0
class PostCountry(Form):
    body = TextAreaField(
        "Add a Title (Optional) <i class='glyphicon glyphicon-info-sign'></i>",
        render_kw={
            "title":
            "Titles help other users more quickly identify news articles."
        })
    urlSite = URLField(
        "Enter URL to be regularly timestamped <i class='glyphicon glyphicon-asterisk'></i>",
        validators=[url(), DataRequired()],
        render_kw={"placeholder": "http://www.example.com"})
    frequency = IntegerField(
        "The frequency (in days) for which timestamps should be created "
        "<i class='glyphicon glyphicon-asterisk'></i>",
        [DataRequired('num required.'),
         validators.NumberRange(min=1, max=30)],
        default=3)
    choice_switcher = RadioField(
        "Country? <i class='glyphicon glyphicon-info-sign'></i>",
        [DataRequired()],
        choices=[('default', 'Compare with the Default location'),
                 ('china', 'Compare with the page in China'),
                 ('usa', 'Compare with the page in USA'),
                 ('uk', 'Compare with the page in UK'),
                 ('russia', 'Compare with the page in Russia')],
        default='default')
    email = EmailField(
        "Notify me in case there is any change in content. (email) "
        "<i class='glyphicon glyphicon-info-sign'></i>",
        render_kw={"placeholder": "*****@*****.**"})
    submit = SubmitField('Submit', render_kw={"onclick": "loading()"})
Ejemplo n.º 18
0
class RegForm(Form):
    login = StringField('Имя пользователя', [validators.Length(min=3, max=25), validators.required()])
    password = PasswordField('Пароль', [
        validators.Length(min=6, max=30),
        validators.required(),
        validators.EqualTo('confirm_password', message='Пароли должны совпадать')]
    )
    confirm_password = PasswordField('Повторите пароль', validators=[
        validators.Length(min=6, max=30),
        validators.required()
    ])
    firstname = StringField('Имя', [validators.Length(min=2, max=30), validators.required()])
    secondname = StringField('Фамилия', [validators.Length(min=2, max=30), validators.required()])
    bday = DateField('Дата рождения', format='%d.%m.%Y')
    sex = RadioField('Пол', choices=[
        (0, 'Мужской'),
        (1, 'Женский')
    ])

    hobbys = SelectMultipleField('Хобби', choices=[
        (0, 'Музыка'),
        (1, 'Театр'),
        (2, 'Кино'),
        (3, 'Цирк'),
        (4, 'Музей'),
        (5, 'Выставка'),
        (6, 'Другое')
    ])
    social_link = StringField('Социальная сеть', validators=[validators.required(), validators.url()])
Ejemplo n.º 19
0
class URL_Status(Form):
    urlSite = URLField(
        "Enter URL to check where it is blocked? <i class='glyphicon glyphicon-asterisk'></i>",
        validators=[url(), DataRequired()],
        render_kw={"placeholder": "http://www.example.com"},
    )
    submit = SubmitField('Search', render_kw={"onclick": "loading()"})
Ejemplo n.º 20
0
class SettingsForm(Form):
    """docstring for SettingsForm"""

    ui_lang = SelectField(
        label=lazy_gettext("Primary site language"),
        description=lazy_gettext("Site will try to show UI labels using this " +
            "language. User data will be shown in original languages."),
    )
    url = URLField(
        label=lazy_gettext("Personal site URL"),
        description=lazy_gettext("If you have personal site and want to share " +
            "with other people, please fill this field"),
        validators=[optional(), url(message=lazy_gettext("Invalid URL."))])
    username = TextField(
        label=lazy_gettext("Public profile address"),
        description=lazy_gettext("Will be part of your public profile URL. Can " +
            "be from 2 up to 40 characters length, can start start from [a-z] " +
            "and contains only latin [0-9a-zA-Z] chars."),
        validators=[
            length(2, 40, message=lazy_gettext("Field must be between 2 and 40" +
            " characters long.")),
            regexp(r"[a-zA-Z]{1}[0-9a-zA-Z]*",
                re.IGNORECASE,
                message=lazy_gettext("Username should start from [a-z] and " +
                    "contains only latin [0-9a-zA-Z] chars"))
        ]
    )
Ejemplo n.º 21
0
def test_valid_url_notld_passes(url_val, dummy_form, dummy_field):
    """
    Require TLD option se to false, correct URL should pass without raising
    """
    validator = url(require_tld=False)
    dummy_field.data = url_val
    validator(dummy_form, dummy_field)
Ejemplo n.º 22
0
class BookmarkForm(FlaskForm):
    url = URLField('Please enter a URL', validators=[DataRequired(), url()])
    description = StringField('Add an optional description')
    tags = StringField('Tags', validators=[Regexp(r'^[a-zA-Z0-9, ]*$',
                                                  message="Tags can only contain letters and numbers")])

    # Override the validate method to add some custom validation not included with WTForms.
    def validate(self):
        # TODO: Improve UX in validating when user doesn't enter a protocol. Fix reappending of incorrect URL form data.
        # if not self.url.data.startswith("http://") or self.url.data.startswith("https://"):
        #     self.url.data = "https://" + self.url.data
        # if not FlaskForm.validate(self):
        #     return False

        if not self.description.data:
            self.description.data = self.url.data

            # filter out empty and duplicate tag names
            # Split the input data at every comma, then remove all whitespace.
            stripped = [t.strip() for t in self.tags.data.split(',')]
            # Then remove all empty strings from the list.
            not_empty = [tag for tag in stripped if tag]
            # Put everything that remains in a set which removes all duplicates.
            tagset = set(not_empty)
            # Put the list of non-empty and non-duplicate tags into a comma separated string again.
            self.tags.data = ",".join(tagset)

        return True
Ejemplo n.º 23
0
class BookmarkForm(FlaskForm):
    url = URLField('The URL for your bookmark',
                   validators=[DataRequired(), url()])
    # if url.error:
    #     print("form: Form errors: {}".format(url.errors))
    # print("dddd")
    description = StringField('description')
    tags = StringField(
        'Tags',
        validators=[
            Regexp(r'^[a-zA-z0-9, ]*$',
                   message="Tags can only contain letters and numbers")
        ])

    def validate(self):
        if not self.url.data.startswith("http://") or \
                self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data

        if not FlaskForm.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        # filter not empty and duplicate tag names
        # print(self.tags.data)
        stripped = [t.strip() for t in self.tags.data.split(",")]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)

        return True
Ejemplo n.º 24
0
class BookmarkForm(FlaskForm):
    """
    bookmark form
    """
    url = URLField('The URL for your bookmark',
                   validators=[DataRequired(), url()])
    description = StringField('Add an optional description')
    tags = StringField('Tags',
                       validators=[
                           Regexp(
                               r'^[a-zA-z0-9, ]*$',
                               message='Tags can only be letters and numbers')
                       ])

    def validate(self):
        """
        custom validator modifies form before validation
        """
        if not (self.url.data.startswith("http://")
                or self.url.data.startswith("https://")):
            self.url.data = "http://" + self.url.data

        if not self.description.data:
            self.description.data = self.url.data

        # filter out empty and dubplicate tags
        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ','.join(tagset)

        return True if FlaskForm.validate(self) else False
Ejemplo n.º 25
0
class MovieCreateForm(BaseForm):
    name = StringField(u'电影名',[required(),length(max=60,message=u'名称太长(不超过60个字符)')])
    year = StringField(u'年份',[regexp('^[0-9]{4}$',message=u"输入四位数字年份")])
    pic = StringField(u'海报',[required(),url(message=u"链接格式无效")])
    info = TextField(u'简介',[required(),length(max=1000,message=u"简介内容太长(不超过1000个字符)")])

    submit = SubmitField(u"保存")
Ejemplo n.º 26
0
class FileForm(Form):
    name = StringField('Name', validators=[DataRequired()])
    url = URLField("Url", validators=[url()])
    category = QuerySelectField('Category:',
                                query_factory=enabled_categories,
                                allow_blank=True)
    submit = SubmitField('Save')
Ejemplo n.º 27
0
class WebhookForm(
        model_form(
            models.Organisation,
            base_class=FlaskForm,
            only=[
                "webhook_enabled",
                "webhook_url",
                "email_notifications_enabled",
                "notification_email",
            ],
            field_args=dict(
                notification_email=dict(
                    render_kw={
                        "data-toggle":
                        "tooltip",
                        "title":
                        "Alternative notification e-mail address (defaut: the technical constact e-mail address)"
                    },
                    validators=[optional(), email()]),
                webhook_url=dict(validators=[optional(), url()])))):
    """Webhoook form."""

    save_webhook = SubmitField(
        "Save",
        render_kw={
            "class": "btn btn-success",
            "data-toggle": "tooltip",
            "title": "Save Organisation webhook"
        })
Ejemplo n.º 28
0
class ProjectForm(FlaskForm):
    filepath = StringField('Filepath', validators=[DataRequired()])
    link = URLField('Url', validators=[url()])
    title = StringField('Title', validators=[DataRequired()])
    language = StringField('Technologies', validators=[DataRequired()])
    caption = StringField('Caption', validators=[DataRequired()])
    submit = SubmitField('Upload to Portfolio')
Ejemplo n.º 29
0
def test_valid_url_passes(url_val, dummy_form, dummy_field):
    """
    Valid url should pass without raising
    """
    validator = url()
    dummy_field.data = url_val
    validator(dummy_form, dummy_field)
Ejemplo n.º 30
0
class BookmarkForm(Form):
    url = URLField('The URL for your bookmark:',
                   validators=[DataRequired(), url()])
    description = StringField('Add an optional description:')
    tags = StringField(
        'Tags',
        validators=[
            Regexp(r'^[A-Za-z0-9, ]*$',
                   message="Tags can only contain letters and numbers")
        ])

    def validate(self):
        if not (self.url.data.startswith("http://")
                or self.url.data.startswith("https://")):
            self.url.data = "http://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        #filter out empty and duplicate tag names
        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)

        return True
Ejemplo n.º 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))
Ejemplo n.º 32
0
 def test_url(self):
     self.assertEqual(url()(self.form, DummyField('http://foobar.dk')), None)
     self.assertEqual(url()(self.form, DummyField('http://foobar.dk/')), None)
     self.assertEqual(url()(self.form, DummyField('http://foobar.museum/foobar')), None)
     self.assertEqual(url()(self.form, DummyField('http://127.0.0.1/foobar')), None)
     self.assertEqual(url()(self.form, DummyField('http://127.0.0.1:9000/fake')), None)
     self.assertEqual(url(require_tld=False)(self.form, DummyField('http://localhost/foobar')), None)
     self.assertEqual(url(require_tld=False)(self.form, DummyField('http://foobar')), None)
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('foobar.dk'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://127.0.0/asdf'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar.d'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar.12'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://localhost:abc/a'))
Ejemplo n.º 33
0
 def conv_URLField(self, model, field, kwargs):
     kwargs["validators"].append(validators.url())
     return f.StringField(**kwargs)
Ejemplo n.º 34
0
 def URL(cls, require_tld=True, message=None):
     ''' Validates an URL address '''
     return validators.url(require_tld, message)
Ejemplo n.º 35
0
 def test_url(self):
     self.assertEqual(url()(self.form, DummyField("http://foobar.dk")), None)
     self.assertEqual(url()(self.form, DummyField("http://foobar.dk/")), None)
     self.assertEqual(url()(self.form, DummyField("http://foobar.museum/foobar")), None)
     self.assertEqual(url()(self.form, DummyField("http://127.0.0.1/foobar")), None)
     self.assertEqual(url()(self.form, DummyField("http://127.0.0.1:9000/fake")), None)
     self.assertEqual(url(require_tld=False)(self.form, DummyField("http://localhost/foobar")), None)
     self.assertEqual(url(require_tld=False)(self.form, DummyField("http://foobar")), None)
     self.assertRaises(ValidationError, url(), self.form, DummyField("http://foobar"))
     self.assertRaises(ValidationError, url(), self.form, DummyField("foobar.dk"))
     self.assertRaises(ValidationError, url(), self.form, DummyField("http://127.0.0/asdf"))
     self.assertRaises(ValidationError, url(), self.form, DummyField("http://foobar.d"))
     self.assertRaises(ValidationError, url(), self.form, DummyField("http://foobar.12"))
     self.assertRaises(ValidationError, url(), self.form, DummyField("http://localhost:abc/a"))
Ejemplo n.º 36
0
 def test_url(self):
     self.assertEqual(url()(self.form, DummyField('http://foobar.dk')), None)
     self.assertEqual(url()(self.form, DummyField('http://foobar.dk/')), None)
     self.assertEqual(url()(self.form, DummyField('http://foobar.museum/foobar')), None)
     self.assertEqual(url()(self.form, DummyField('http://127.0.0.1/foobar')), None)
     self.assertEqual(url()(self.form, DummyField('http://127.0.0.1:9000/fake')), None)
     self.assertEqual(url(require_tld=False)(self.form, DummyField('http://localhost/foobar')), None)
     self.assertEqual(url(require_tld=False)(self.form, DummyField('http://foobar')), None)
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('foobar.dk'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://127.0.0/asdf'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar.d'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://foobar.12'))
     self.assertRaises(ValidationError, url(), self.form, DummyField('http://localhost:abc/a'))
     # Test IDNA
     IDNA_TESTS = (
         u'http://\u0645\u062b\u0627\u0644.\u0625\u062e\u062a\u0628\u0627\u0631/foo.com',  # Arabic test
         u'http://उदाहरण.परीक्षा/',  # Hindi test
         u'http://실례.테스트',  # Hangul test
     )
     for s in IDNA_TESTS:
         self.assertEqual(url()(self.form, DummyField(s)), None)
Ejemplo n.º 37
0
def convert_LinkProperty(model, prop, kwargs):
    """Returns a form field for a ``db.LinkProperty``."""
    kwargs['validators'].append(validators.url())
    return get_TextField(kwargs)
Ejemplo n.º 38
0
 def __call__(self, handler_class):
     spec = url(self.pattern, handler_class, self.kwargs, name=self.name)
     self._routes.setdefault(self.host, []).append(spec)
     return handler_class
Ejemplo n.º 39
0
 def conv_URLField(self, model, field, kwargs):
     kwargs['validators'].append(validators.url())
     return f.TextField(**kwargs)
Ejemplo n.º 40
0
TelephoneField = partial(StringField, validators=[
                data_required(message=u'座机号码为空'),
                telephone_number(message=u'座机号码格式错误')
            ])

EmailField = partial(StringField, validators=[
                data_required(message=u'邮箱为空'),
                email(message=u'邮箱格式错误')
            ])

CaptchaField = partial(StringField, validators=[
                data_required(message=u'验证码为空'),
                captcha(message=u'验证码格式错误')
            ])

PasswordField = partial(StringField, validators=[
                data_required(message=u'密码为空'),
                password(message=u'密码格式错误')
            ])

HashPasswordField = partial(StringField, validators=[
                data_required(message=u'密码为空'),
                hash_password(message=u'密码格式错误')
            ])

URLField = partial(StringField, validators=[
                data_required(message=u'网址为空'),
                url(message=u'网址格式错误')
            ])