-1

I am new to python and Django, i wanted to know how below thing can be possible?

input field 1 - Enter name - abc@yoyo.com
input field 2 - Enter Url - www.yoyo.com
 Submit button

so I want to validate the email domain and the URL name is same. Suppose if abc@yoyo.com is not similar to the URL field (www.yo.com) so show an error. else if it's same then proceed.

How can this be implemented in Django?

  • If you need to do validation that depends on more than one field, use the form's `clean()` method. See the [django docs](https://docs.djangoproject.com/en/2.2/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other) – John Gordon Sep 19 '19 at 18:26
  • @JohnGordon i am new to this, so a pseudo code would be better for my understanding. – Tamanbir Singh Sep 19 '19 at 18:28
  • 1
    Go to the page I linked. It's better than any example I could make up. – John Gordon Sep 19 '19 at 18:29

2 Answers2

0

You could do this in either the front end or backend

Frontend implementation with Javascript.

<input id="email" type="text"> <br>
<input id="domain_id" type="text" onblur="checkDomain()">

<button type="button">Submit</button>

<script>
function checkDomain() {
  var domain = document.getElementById("email").value.split("@")[1];
  var domain2 = document.getElementById("domain_id").value;

  if (domain != domain2){
  alert("Domains don't match"); 
  }

}
</script>

Backend implementation in Django (assumes use of Django Forms)

You would put this in your forms.py within your form.

    def clean_domain(self):
        email = self.cleaned_data.get('email')
        domain= self.cleaned_data.get('domain')
        email_domain = #some method to get the domain of the email
        if email_domain != domain:
            raise forms.ValidationError(u'The domain must match the domain in your email')
        return domain

Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35
0

Here is the new answer based on your latest comments:

<input id="email" type="text"> <br>
<input id="domain_id" type="text" onblur="checkDomain()">

<button id="myBtn" type="button">Submit</button>

<script>
document.getElementById("myBtn").disabled = true;
function checkDomain() {
  var domain = document.getElementById("email").value.split("@")[1];
  var domain2 = document.getElementById("domain_id").value;

  if (domain != domain2){
  alert("Domains don't match"); 
  }
  else {
  document.getElementById("myBtn").disabled = false;
  }

}
</script>
Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35