How do I validate wtforms fields against one another?

前端 未结 3 1235
感情败类
感情败类 2020-12-10 11:09

I have three identical SelectField inputs in a form, each with the same set of options. I can\'t use one multiple select.

I want to make sure that the u

3条回答
  •  青春惊慌失措
    2020-12-10 11:38

    I wrote a small python library required to make cross-field validation like this easier. You can encode your validation logic declaratively as pairwise dependencies. So your form may look like:

    from required import R, Requires, RequirementError
    
    class MyForm(Form):
    
        VALIDATION = (
            Requires("select1", R("select1") != R("select2") +
            Requires("select2", R("select2") != R("select3") +
            Requires("select3", R("select3") != R("select1")
        )
    
        select1 = SelectField('Select 1', ...)
        select2 = SelectField('Select 2', ...)
        select3 = SelectField('Select 3', ...)
    
        def validate(self):
            data = {
                "select1": self.select1.data,
                "select2": self.select2.data,
                "select3": self.select3.data,
            }
    
            # you can catch the RequirementError
            # and append the error message to 
            # the form errors
    
            self.VALIDATION.validate(data)
            return result
    

    You can take the VALIDATION object and append more validation rules or even put it in a separate module and import / reuse validation rules in different places.

提交回复
热议问题