-1

I am trying to incorporate a regex check for user input in my class. I want a scenario where users can't proceed to enter their name until they enter a valid email address. The current code i have isn't working as expected.

I suppose a while-loop is in order here but i am struggling to implement that in this class. Any assistance is much appreciated.

class test:  
 def __init__(self):     
    self.email = input("Enter your email: ")
    email_check = re.search(r'[\w.-]+@[\w.-]+.\w+', self.email)
    if email_check:
        print ('email valid')
    else:
        print ('email not valid')
        self.email = input("Enter your email: ")            
        sys.exit(0)
     self.name = input("Enter your name:  ")        
jebjeb
  • 115
  • 1
  • 4
  • 12

5 Answers5

1

You can do it like this.

while True:
    self.email = input ("Enter email:")
    if valid_email:
        break

Substitute valid_email with your way of validating the email address.

You may also be interested in Python check for valid email address? for ways to validate an email address.

v7d8dpo4
  • 1,399
  • 8
  • 9
0

First of all - you should not implement any activity of this kind into __init__ method, as one is intended for object fields initialization first place. Consider dedicated 'check_email' method, or whatever name applies best.

Now, regarding your case:

class test:
    def __init(self):
       # whatever initialization applies
       pass

    def init_emails():
        emails = []
        proceed = True
        # if you really in need of do/while loop
        while proceed:
            email = self.input_email()
            # your logic for input
            if email is not None:
                emails.append(email)
            # invalid input or cancel
            else:
                 proceed = False
        return input

     def input_email(self):
         value = input('Enter your email:')
         # TODO: validate/check input
         return proper_value
agg3l
  • 1,444
  • 15
  • 21
  • I second the comments that this doesn't belong in `__init__` or probably even in a class at all. User interaction should probably happen outside the class unless it is specifically a class to implement user interaction. Your class should probably just `raise` an error if it finds itself populated with invalid data. – tripleee Oct 11 '16 at 03:49
0
   class test:  
     def __init__(self):     
         self.email = self.get_name()

     def get_name(self) :
         while True:
            x = input("Enter your email: ")
            if (re.search(r'[\w.-]+@[\w.-]+.\w+', x)) :
                return x
Ajay Pal
  • 543
  • 4
  • 13
0

This script functions as described, in the end printing the name and email. If you need to use python2.7, use raw_input instead of input. I used for i in range instead of while True to avoid an endless loop.

#!/usr/bin/env python3

import re
import sys


class Test(object):
    def __init__(self):
        self.email = None
        self.name = None

    def get_email(self):
        for i in range(3):
            email = input('Enter your email: ')
            if re.search('[\w.-]+@[\w.-]+.\w+', email):
                return email
        print('Too many failed attempts!')
        sys.exit(1)

    def get_name(self):
        for i in range(3):
            name = input('Enter your name: ')
            if name:
                return name
            print('Too many failed attempts!')
            sys.exit(1)

    def initialize(self):
        self.email = self.get_email()
        self.name = self.get_name()
        print('"{}" <{}>'.format(self.name, self.email))


if __name__ == '__main__':
    t = Test()
    t.initialize()
mgwilliams
  • 78
  • 1
  • 2
0

Instead of input, try to use raw_input. Like this:

self.email = raw_input("Enter your email:")

There'll be no error anymore. Hope this helps.

Harv
  • 446
  • 5
  • 12
  • 1
    In Python 3, 'input` is the equivalent of Python 2's `raw_input` (see https://www.python.org/dev/peps/pep-3111/). Based on the usage of the print function (rather than statement) in the original code, I would assume the OP is using Python 3. – mgwilliams Oct 11 '16 at 05:15