Reputation: 13
I have a django form that I'm outputing no problem.
My question is with regard to jQuery Validation.
I want to apply jQuery validation to inputs that are required.
I'm using http://docs.jquery.com/Plugins/validation
There's no field.is_required that I can use in the template
so I'm using the help_text and evaluating that in my template.
Just wondering if this is the best way to go about this?
Any advise much appreciated.
Here is:
1) Form Class
class UserDetailsForm(forms.Form):
city_town = forms.CharField(label='City / Town',max_length=100, required=True, help_text='*')
state_province = forms.CharField(label='State / Province',max_length=100, required=True, help_text='*')
2) Form output
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field.help_text }} {{ field }}
</div>
{% endfor %}
3) Form jQuery Validation
// Form Validation Setup
{% for field in form %}
{% if field.help_text == '*' %}
$("input[name='{{ field.html_name }}']").addClass('required');
{% endif %}
{% endfor %}
$("#updateProfileForm").validate();
Is there any better method than the this work around I'm using:
if field.help_text == '*'
I may want to use that field for a tool tip of something later
but for now I'm using an asterisk so I can use it in a loop for jQuery validation
in the template.
Thanks!
Upvotes: 1
Views: 619
Reputation: 32532
When you iterate through a form instance, the __iter__
method returns a BoundField
(that handles the rendering and other misc items). This bound field has a field attribute that stores the actual field instance (which does store the required attribute). So you can do
{% if field.field.required %}
$("input[name='{{ field.html_name }}']").addClass('required');
{% endif %}
Upvotes: 2
Reputation: 5842
Just add this to your model. This will add the class 'required'
to your form.
city_town.widget.attrs['class'] = 'required'
Upvotes: 1