I built a custom validator that checks if a user input exists in a database. Now I want to add a custom field flag that pops up if the validation is not successful (without re-rendering html), similar to the 'required' flag in the InputRequired validator.
Here's my validator:
class ProjectExists(object):
field_flags = ('project_not_exists', ) # need the custom flag here
def __init__(self, project_code=None, message=None):
self.project_code = project_code
self.message = message
self.conn, self.cur = connect_db()
def __call__(self, form, field):
code = field.data
self.cur.execute("SELECT 1 FROM database WHERE project_code = '{}'".format(code))
code_check = self.cur.fetchall()
if not code_check:
if self.message is None:
self.message = field.gettext('Project code {} does not exists!'.format(code))
raise StopValidation(self.message)
Here's the source code for the InputRequired validator for reference:
class InputRequired(object):
field_flags = ('required', )
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
if not field.raw_data or not field.raw_data[0]:
if self.message is None:
message = field.gettext('This field is required.')
else:
message = self.message
field.errors[:] = []
raise StopValidation(message)
Appreciate your help!
Got it working with Parsley , checking against an existing endpoint if a project code exists.
WTForm:
class ViewForm(FlaskForm):
project_code = StringField('Project Code',
render_kw={'required':"", 'data-parsley-project-check':""})
JavaScript:
$(function () {
Parsley.addValidator('projectCheck', {
validateString: function(value) {
console.log("validating")
var send = {
id: value,
}
var url = '/projects/'
return $.getJSON(url, send, function(data) {
}).then(function(json) {
if (!json['features']) {
return $.Deferred().reject()
}
})
},
messages: {
en: 'Project code does not exist!'
}
})})
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.