Python wtforms.validators.Length() Examples

The following are 20 code examples of wtforms.validators.Length(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wtforms.validators , or try the search function .
Example #1
Source File: user_controller.py    From codecat with GNU General Public License v3.0 6 votes vote down vote up
def List_table_users():
    
    if check_auth() == False:
        return redirect("front/auth")

    class TheForm(Form): 
        name = TextField('id:', validators=[validators.required(), validators.Length(min=1, max=9)])

        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    obj=user_rest_api
    obj=obj.rest_call("","")
    obj.token=session['userkey']
    obj.List_Users()
    users=[]
    for rows in obj.json_output:
        users.append({"id": rows[0],"name": rows[1],"email": rows[2],"owner": rows[3],"date": rows[4]})
    return render_template('user_forms/user_list.html',form=form, users=users, title="Table of Users") 
Example #2
Source File: rule_controller.py    From codecat with GNU General Public License v3.0 6 votes vote down vote up
def List_table_rules():
    class TheForm(Form): 
        rule = TextField('id:', validators=[validators.required(), validators.Length(min=1, max=32)])

        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    if user_controller.check_auth() == False:
        return redirect("front/auth")

    obj=rule_rest_api
    obj=obj.rest_call("","")
    obj.token=session['userkey']
    obj.List_rules()
    rules=[]
    for rows in obj.json_output:
        rules.append(rows)
    return render_template('rule_forms/rule_list.html',form=form, rules=rules, title="Table of rules") 
Example #3
Source File: forms.py    From notifications-admin with MIT License 6 votes vote down vote up
def validate(self):

        if self.contact_details_type.data == 'url':
            self.url.validators = [DataRequired(), URL(message='Must be a valid URL')]

        elif self.contact_details_type.data == 'email_address':
            self.email_address.validators = [DataRequired(), Length(min=5, max=255), ValidEmail()]

        elif self.contact_details_type.data == 'phone_number':
            # we can't use the existing phone number validation functions here since we want to allow landlines
            def valid_phone_number(self, num):
                try:
                    normalise_phone_number(num.data)
                    return True
                except InvalidPhoneError:
                    raise ValidationError('Must be a valid phone number')
            self.phone_number.validators = [DataRequired(), Length(min=5, max=20), valid_phone_number]

        return super().validate() 
Example #4
Source File: orm.py    From jbox with MIT License 5 votes vote down vote up
def convert(self, model, field, field_args):
        kwargs = {
            'label': field.verbose_name,
            'description': field.help_text,
            'validators': [],
            'filters': [],
            'default': field.default,
        }
        if field_args:
            kwargs.update(field_args)

        if field.blank:
            kwargs['validators'].append(validators.Optional())
        if field.max_length is not None and field.max_length > 0:
            kwargs['validators'].append(validators.Length(max=field.max_length))

        ftype = type(field).__name__
        if field.choices:
            kwargs['choices'] = field.choices
            return f.SelectField(**kwargs)
        elif ftype in self.converters:
            return self.converters[ftype](model, field, kwargs)
        else:
            converter = getattr(self, 'conv_%s' % ftype, None)
            if converter is not None:
                return converter(model, field, kwargs) 
Example #5
Source File: user_controller.py    From codecat with GNU General Public License v3.0 5 votes vote down vote up
def delete_user(request):
    if check_auth() == False:
        return redirect("front/auth")
    class TheForm(Form): 
        id = TextField('id:', validators=[validators.required(), validators.Length(min=1, max=64)])

        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    if request.method == 'POST':
        token=request.form['csrf_token']
 
        if form.validate():
            if form.csrf_token.errors: 
                flash('Error: form token invalid try to post again')
            else:
                id=request.form['id']
                obj=user_rest_api
                obj=obj.rest_call("","")
                obj.token=session['userkey']
                handler=obj.Delete_User(id)
                flash(str(handler))
        else:
            flash('Error: All the form fields are required. ')
    return render_template('user_forms/user_delete.html', form=form, title="Delete User by ID") 
Example #6
Source File: user_controller.py    From codecat with GNU General Public License v3.0 5 votes vote down vote up
def insert_user(request):
    if check_auth() == False:
        return redirect("front/auth")

    class TheForm(Form): 
        name = TextField('name:', validators=[validators.required(), validators.Length(min=4, max=35)])
        email = TextField('email:', validators=[validators.required(), validators.Length(min=4, max=35)])
        password = TextField('password:', validators=[validators.required(), validators.Length(min=4, max=35)]) 
        # owner = TextField('owner:', validators=[validators.required(), validators.Length(min=4, max=12)])
        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    if request.method == 'POST':
        token=request.form['csrf_token']
 
        if form.validate():
            if form.csrf_token.errors: 
                flash('Error: form token invalid try to post again')
            else:
                name=request.form['name']
                email=request.form['email']
                owner=request.form['owner']
                password=request.form['password']
                obj=user_rest_api
                obj=obj.rest_call("","")
                obj.token=session['userkey']
                handler=obj.Insert_User(email,name,password,owner)
                flash(str(handler))
        else:
            flash('Error: All the form fields are required. ')
    return render_template('user_forms/user_insert.html', form=form, title="Insert User") 
Example #7
Source File: user_controller.py    From codecat with GNU General Public License v3.0 5 votes vote down vote up
def show_auth(request):
    if session.get('userkey') == True:
        if test_token(session['userkey'])==True:
            img='<img src="/static/codecat1.png" height="400" width="400" >'
            return render_template('AuthAdmin.html',title="Welcome to Codecat",content=img)

    class TheForm(Form):
        email = TextField('email:', validators=[validators.required(), validators.Length(min=4, max=35)])
        password = TextField('password:', validators=[validators.required(), validators.Length(min=4, max=35)])

        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )
    if request.method == 'POST':
        token=request.form['csrf_token']
 
        if form.validate():
            if form.csrf_token.errors: 
                flash('Error: form token invalid try to post again')
                return render_template('login.html',form=form)
            if test_auth(request) == True:
                img='<img src="/static/codecat1.png" height="400" width="400" >'
                return render_template('AuthAdmin.html',title="Welcome to Codecat",content=img)
            flash('Error user or password not found !')
        else:
            flash('Error: All the form fields are required. ')
# token in  form.csrf_token 
    return render_template('login.html',form=form) 
Example #8
Source File: rule_controller.py    From codecat with GNU General Public License v3.0 5 votes vote down vote up
def delete_rule(request):
    if user_controller.check_auth() == False:
        return redirect("front/auth")

    class TheForm(Form): 
        id = TextField('id:', validators=[validators.required(), validators.Length(min=1, max=64)])

        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    if request.method == 'POST':
        token=request.form['csrf_token']
 
        if form.validate():
            if form.csrf_token.errors: 
                flash('Error: form token invalid try to post again')
            else:
                id=request.form['id']
                obj=rule_rest_api
                obj=obj.rest_call("","")
                obj.token=session['userkey']
                handler=obj.Delete_rule(id)
                flash(str(handler))
        else:
            flash('Error: All the form fields are required. ')
    return render_template('rule_forms/rule_delete.html', form=form, title="Delete rule by ID") 
Example #9
Source File: rule_controller.py    From codecat with GNU General Public License v3.0 5 votes vote down vote up
def insert_rule(request):
    if user_controller.check_auth() == False:
        return redirect("front/auth")

    class TheForm(Form): 
        title = TextField('title:', validators=[validators.required(), validators.Length(min=3, max=1024)])
        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    if request.method == 'POST':
        token=request.form['csrf_token']
        if form.validate():
            if form.csrf_token.errors: 
                flash('Error: form token invalid try to post again')
            else:
                try:
                 d={}
                 d['title']=request.form['title']
                 d['lang']=request.form['lang']
                 d['description']=request.form['description']
                 d['level']=request.form['level']
                 d['match1']=request.form['match1']
                 d['match2']=request.form['match2']
                 obj=rule_rest_api
                 obj=obj.rest_call("","")
                 obj.token=session['userkey']
                 handler=obj.Insert_rule(**d)
                 flash(str(handler))
                except Exception as e:
                 flash('Fail: '+ str(e))
        else:
            flash('Error: All the form fields are required. ')
    return render_template('rule_forms/rule_insert.html', form=form, title="Insert rule") 
Example #10
Source File: engine_controller.py    From codecat with GNU General Public License v3.0 5 votes vote down vote up
def allsinks(request):
    if user_controller.check_auth() == False:
        return redirect("front/auth")
    class TheForm(Form):
        path = TextField('path:', validators=[validators.required(), validators.Length(min=1, max=2048)])
        lang = TextField('lang:', validators=[validators.required(), validators.Length(min=1, max=32)])
        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    if request.method == 'POST':
        token=request.form['csrf_token']
        if form.validate():
            if form.csrf_token.errors: 
                flash('Error: form token invalid try to post again')
            else:
                try:
                 d={}
                 d['lang']=request.form['lang']
                 d['path']=request.form['path']
                 obj=engine_rest_api
                 obj=obj.rest_call("","")
                 obj.token=session['userkey']
                 codes_lines=obj.allsinks(**d)
                 flash("Wait five seconds and look the code cache")
                except Exception as e:
                 flash('Fail: '+ str(e))
        else:
            flash('Error: All the form fields are required. ')
    return render_template('engine_forms/allsinks.html', form=form, title="Search using all rules") 
Example #11
Source File: engine_controller.py    From codecat with GNU General Public License v3.0 5 votes vote down vote up
def getsinks(request):
    if user_controller.check_auth() == False:
        return redirect("front/auth")
    class TheForm(Form):
        sink = TextField('sink:', validators=[validators.required(), validators.Length(min=1, max=1024)])
        path = TextField('path:', validators=[validators.required(), validators.Length(min=1, max=2048)])
        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )

    if request.method == 'POST':
        token=request.form['csrf_token']
        if form.validate():
            if form.csrf_token.errors: 
                flash('Error: form token invalid try to post again')
            else:
                try:
                 d={}
                 d['lang']=request.form['lang']
                 d['sink']=request.form['sink']
                 d['path']=request.form['path']
                 obj=engine_rest_api
                 obj=obj.rest_call("","")
                 obj.token=session['userkey']
                 codes_lines=obj.getsinks(**d) 
                 flash("Wait five seconds and look the code cache")     
                except Exception as e:
                 flash('Fail: '+ str(e))
        else:
            flash('Error: All the form fields are required. ')
    return render_template('engine_forms/getsinks.html', form=form, title="Search sink") 
Example #12
Source File: forms.py    From notifications-admin with MIT License 5 votes vote down vote up
def password(label='Password'):
    return PasswordField(label,
                         validators=[DataRequired(message='Cannot be empty'),
                                     Length(8, 255, message='Must be at least 8 characters'),
                                     CommonlyUsedPassword(message='Choose a password that’s harder to guess')]) 
Example #13
Source File: orm.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def convert(self, model, field, field_args):
        kwargs = {
            'label': field.verbose_name,
            'description': field.help_text,
            'validators': [],
            'filters': [],
            'default': field.default,
        }
        if field_args:
            kwargs.update(field_args)

        if field.blank:
            kwargs['validators'].append(validators.Optional())
        if field.max_length is not None and field.max_length > 0:
            kwargs['validators'].append(validators.Length(max=field.max_length))

        ftype = type(field).__name__
        if field.choices:
            kwargs['choices'] = field.choices
            return f.SelectField(**kwargs)
        elif ftype in self.converters:
            return self.converters[ftype](model, field, kwargs)
        else:
            converter = getattr(self, 'conv_%s' % ftype, None)
            if converter is not None:
                return converter(model, field, kwargs) 
Example #14
Source File: orm.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def _string_common(cls, column, field_args, **extra):
        if column.type.length:
            field_args['validators'].append(validators.Length(max=column.type.length)) 
Example #15
Source File: admin.py    From maple-blog with GNU General Public License v3.0 5 votes vote down vote up
def scaffold_form(self):
        form_class = super(UserView, self).scaffold_form()
        form_class.password = PasswordField(
            "Password", [DataRequired(), Length(min=4, max=20)])
        return form_class 
Example #16
Source File: orm.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def convert(self, model, field, field_args):
        kwargs = {
            'label': field.verbose_name,
            'description': field.help_text,
            'validators': [],
            'filters': [],
            'default': field.default,
        }
        if field_args:
            kwargs.update(field_args)

        if field.blank:
            kwargs['validators'].append(validators.Optional())
        if field.max_length is not None and field.max_length > 0:
            kwargs['validators'].append(validators.Length(max=field.max_length))

        ftype = type(field).__name__
        if field.choices:
            kwargs['choices'] = field.choices
            return f.SelectField(**kwargs)
        elif ftype in self.converters:
            return self.converters[ftype](model, field, kwargs)
        else:
            converter = getattr(self, 'conv_%s' % ftype, None)
            if converter is not None:
                return converter(model, field, kwargs) 
Example #17
Source File: orm.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def _string_common(cls, column, field_args, **extra):
        if column.type.length:
            field_args['validators'].append(validators.Length(max=column.type.length)) 
Example #18
Source File: orm.py    From jbox with MIT License 5 votes vote down vote up
def _string_common(cls, column, field_args, **extra):
        if column.type.length:
            field_args['validators'].append(validators.Length(max=column.type.length)) 
Example #19
Source File: remedy_utils.py    From radremedy with Mozilla Public License 2.0 4 votes vote down vote up
def get_field_args(field, **kwargs):
    """
    Generates a dictionary of arguments to be used when
    rendering out a form field.

    Args:
        field: The form field to render.
        **kwargs: Any additional arguments to include for the form field.

    Returns:
        A dictionary of arguments to use to render out a form field.
    """
    # Set up our default args
    field_args = {
        "class_": "form-control"
    }

    # Handle required fields
    if field.flags.required:
        field_args['required'] = 'required'

    # Look at field validators
    for val in field.validators:
        # Handle minlength/maxlength attributes if specified on
        # string fields through a Length validator
        if isinstance(val, Length):
            if val.min > 0:
                field_args['minlength'] = val.min
            if val.max > 0:
                field_args['maxlength'] = val.max
        elif isinstance(val, Email):
            field_args['type'] = 'email'
        elif isinstance(val, URL):
            field_args['type'] = 'url'
        elif isinstance(val, NumberRange):
            if val.min is not None:
                field_args['min'] = val.min
            if val.max is not None:
                field_args['max'] = val.max

    # If we have a description, create an aria-described by attribute
    if field.description and len(field.description) > 0:
        field_args['aria-describedby'] = field.id + '_help'

    # Merge in extra arguments
    field_args.update(kwargs)

    # Default rows for textareas if not specified
    if 'rows' not in field_args and field.type == 'TextAreaField':
        field_args['rows'] = '3'

    return field_args 
Example #20
Source File: user_controller.py    From codecat with GNU General Public License v3.0 4 votes vote down vote up
def update_user(user_id):
    if check_auth() == False:
        return redirect("front/auth")
    class TheForm(Form): 
        name = TextField('name:', validators=[validators.required(), validators.Length(min=4, max=35)])
        email = TextField('email:', validators=[validators.required(), validators.Length(min=4, max=35)])
        password = TextField('password:', validators=[validators.required(), validators.Length(min=4, max=35)]) 
        # owner = TextField('owner:', validators=[validators.required(), validators.Length(min=4, max=12)])
        class Meta:
            csrf = True
            csrf_class = tokenform.Ice_CSRF

    form = TheForm(
      request.form,
      meta={'csrf_context': request.remote_addr }
    )
    
    if request.method == 'POST': 
#"csrf_token" in request.form:
        if len(str(user_id)) >=1 and len(request.form['csrf_token']) > 1 :
            token=request.form['csrf_token']
 
            if form.validate():
                if form.csrf_token.errors: 
                    flash('Error: form token invalid try to post again')
                else:
                    name=request.form['name']
                    email=request.form['email']
                    owner=request.form['owner']
                    password=request.form['password']
                    obj=user_rest_api
                    obj=obj.rest_call("","")
                    obj.token=session['userkey']
                    handler=obj.Update_User(str(user_id),email,name,password,owner)
                    flash(str(handler))
            else:
                flash('Error: All the form fields are required. ')
    obj=user_rest_api
    obj=obj.rest_call("","")
    obj.token=session['userkey']
    obj.Return_User_by_ID(str(user_id))
    users={}
    rows=[]
    rows= obj.json_output
    users={"id": str(rows[0]),"name": str(rows[1]),"email": str(rows[2]),"owner": str(rows[3]),"date": str(rows[4]) }
    return render_template('user_forms/user_update.html', form=form, users=users, title="Update data of user")