Greetings folks,
  I recently had a requirement to validate certain fields based on the
values of others. Something like
     if fields['type'] == 'Enhancement': validate (field['version'])

  There was a lack of information regarding this on the wiki as well
as the group. I got a pointer to FieldsMatch which I was able to
cannibalise and create a FormValidator that could look at the entire
form to perform this kind of validation. I'm posting an example below.
This is TG1.0.4.4

*  The first thing you'll want to do is to create a validator for your
form. This is done by subclassing the
turbogears.validators.FormValidator class into your own validator
(FieldsMatch does this). Here is an example

class SampleValidator(turbogears.validators.FormValidator):
   show_match = True # I'm not sure what this does. Blindly copied
from FieldsMatch
   validator_partial_form = True # To allow validation of partial
forms.
   field_names = ['type','version'] # List of fields which we need to
perform this validation.

   def validate_partial(self,field_dict,state):
     for name in self.field_names:
       if name not in self.field_names: return # This validator cannot
run so return None (no errors)
     self.validate_python (field_dict, state)

  def  validate_python(self,field_dict,state):
    error_dict = {} # Dict to hold validation errors
    if field_dict['type'] == 'Enhancement':
       if field_dict['version'] == "1.1":
         error_dict ['version'] = "1.1 cannot accept enhancements"
         raise turbogears.validators.Invalid ("Error in
form",field_dict, state,error_dict)

* That should take care of your validator. Now what you need to do is
to create a schema for your form like so

class BugCreationValidationSchema(turbogears.validators.Schema):
   chained_validators = [SampleValidator()] # This will contain a list
of validators that will run on the entire form.
   creator = turbogears.validators.NotEmpty() # Other validators for
normal fields. This is just an example

* Now, when you create your TableForm or ListForm, you need to pass
this as a 'validator' like so
   form = TableForm("bugcreate",fields = BugCreationFields, method =
'post', action = "/create", validator = BugCreationValidationSchema(),
submit_text = "create bug")

* This form will handle the conditional validation

I don't think I've missed anything but if people run into problems,
please update the thread. Once it's got some more meat on it, I'll put
it up on the Wiki.

Thanks.






--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to