I've got a really big ModelForm and want to implement Ketchup jquery validation. I have to add a data-validate=
onto every form field I want validated and it's getting laborious to say the least.
At the moment I have something like this:
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
def __init__(self, *args, **kwargs):
super(AuthorForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['data-validate'] = 'validate(required)'
self.fields['email'].widget.attrs['data-validate'] = 'validate(required, email)'
self.fields['is_alive'].widget.attrs['data-validate'] = 'validate(minselect(1))'
self.fields['telephone'].widget.attrs['class'] = 'telephone'
self.fields['telephone'].widget.attrs['data-validate'] = 'validate(required开发者_如何学Go)'
But with about another 20 fields to go I'm wondering if there's an easier way to be adding these attributes to the fields I want validated. (Not all fields have to be validated, they can be blank)
Not even knowing what Ketchup is, I clicked on your link and found an example on how to do it w/o attributes on the fields, that is, by passing it in to the ketchup() method:
"Right after the options (empty here {}) we pass in an object. Use the key to declare the jQuery selector on which fields the validations in the value are processed. Validations declared like this don't need the validate() indicator."
$('#fields-in-call').ketchup({}, {
'.required' : 'required', //all fields in the form with the class 'required'
'#fic-username': 'username, minlength(3)' //one field in the form with the id 'fic-username'
});
If you're looking for alternative libraries, I would opt for jQuery.validate
精彩评论