I am trying to create a custom URL validator for a form input field but validator does not seem to work. I applied a DataRequired()
to the StringField
which works fine but the custom validator does not. Here is code:
def validate_domain(form, field):
url_regex = r'''((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.
([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*'''
regex = re.compile(url_regex)
url = regex.match(field.data).group()
if url:
field.data = 'http://' + urlparse(url).netloc
else:
raise ValidationError('Please enter a valid URL.')
class SubmitDomainForm(Form):
domain = StringField('Domain', validators=[DataRequired(),
validate_domain])
submit = SubmitField('Crawl')
HTML for the same:
{% extends "layout.html" %}
{% block content %}
<div class="content-section">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<legend class="border-bottom mb-4">{{ legend }}</legend>
<div class="form-group">
{{ form.domain.label(class="form-control-label") }}
{% if form.domain.errors %}
{{ form.domain(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.domain.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.domain(class="form-control form-control-lg") }}
{% endif %}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
{% endblock content %}
Even when I submit a non URL input the form just submits. I am unable to get what seem to going wrong here.
After testing my comment it seems that multi-lining your regex is likely causing you an issue
import re
from urllib.parse import urlparse
data = 'https://google.com/#resource'
url_regex = r'''((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*'''
regex = re.compile(url_regex)
url = regex.match(data).group()
print('http://' + urlparse(url).netloc)
the above code works for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.