Search code examples
pythonmongodbmongoenginedocuments

StringField in mongodb requirements


I am wondering if I can add a requirment to the setup of my User document to check for a specific string. The idea is when a User Document is created with an email address, I want to make sure the email is from a college so it should end in ".edu" example: "john.doe@college.edu" is acceptable but "john.doe@gmail.com" is not

Here is my code:

class User(db.Document, UserMixin):
    name = db.StringField(max_length=255, unique=True)
    email = db.StringField(max_length=255, unique=True)
    phone = db.StringField(max_length=255, unique=True)
    password = db.StringField(max_length=255)
    active = db.BooleanField(default=True)
    confirmed_at = db.DateTimeField()
    roles = db.ListField(db.ReferenceField(Role), default=[])

Solution

  • There is an optional regex argument you can define:

    email = db.StringField(max_length=255, unique=True, regex=r'.*?boston\.edu$')
    

    And, also, why not use a specific EmailField in this case:

    email = db.EmailField(max_length=255, unique=True, regex=r'.*?boston\.edu$')