0

I have a template that has a form with two input boxes. The problem is that I need to ensure that only one of either box has a filled value. That is, one text box should be empty. Since Django doesn't provide this kind of an OR mechanism, I am checking this through Javascript in the template:

function validateData() {
    if ($("#email").val() && $("#cellno").val()){
        alert("Please Enter either E-Mail Address or Cell Number");
    } else {
        alert("Form submitted successfully");
        // redirect to view_2
    }
}

The issue is that I want to send the data from the textbox to view_2. How can I send the value of the textbox and also perform the validation? Without the JS validation I could have simply added the url to the form action.

4
  • Have a look at django forms: docs.djangoproject.com/en/1.8/topics/forms Commented Jul 10, 2015 at 9:17
  • Have another look at my question. Commented Jul 10, 2015 at 9:20
  • You are missing the closing } for your function. My brain immediatelly return a parse error when I read that code :) Commented Jul 10, 2015 at 9:25
  • @randomnessrandomly Django provides a mechanism to verify the data through forms, cf my link Commented Jul 10, 2015 at 9:35

2 Answers 2

4

I'm not sure what you mean by 'Django doesn't provide this kind of or mechanism'. If you're using Django forms in your view, you can write a clean method that validates fields that depend on each other.

class MyForm(forms.Form):
    email = forms.EmailField(required=False)
    cell = forms.CharField(required=False, max_length=20)

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        if cleaned_data.get('email') and cleaned_data.get('cell'):
            raise forms.ValidationError("Please select either E-mail address or cell number, but not both")
        return cleaned_data
Sign up to request clarification or add additional context in comments.

1 Comment

I like this better than my answer. Clear solution with Django.
1

I would say you should attach your function to the submit event and prevent submitting when validation fails.

Maybe something like this:

$("form").submit(function(event) {
    if ($("#email").val() && $("#cellno").val()){
        alert("Please Enter either E-Mail Address or Cell Number");
        event.preventDefault(); // this prevents the submitting.
    } else {
        alert("Form submitted successfully");
    }
});

1 Comment

@Alasdair Oh, thank you. You are certainly right. The form should not be submitted in the if branch. I am editing that right now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.