3

I use python 2.7.12 with pymongo 2.8.1, django 1.11.7, mongoengine 0.9.0 and mongodb 3.4.10. I am creating a custom user model which inserts documents in a regular mongodb collection. I inherited the 'Document' class from mongoengine to create the string password field. I've been trying to create a regex pattern for the following conditions:

  • Length: 8-25 characters
  • At least 1 uppercase letter
  • At least 1 lowercase letter
  • At least 1 number
  • At least 1 special character

I tried using re.compile() in the following way:

import re
regexp = re.compile('[A-Za-z0-9@#$%^&+=]', max_length=25, min_length=8)
password = StringField(regex=regexp)

I sent HTTP POST requests with invalid passwords and it only throws an error when the length is lesser than 8 or greater than 25, otherwise they pass. I'm new to mongoengine and I'm not really sure what kind of input the regex parameter takes, neither have I been able to find examples for StringField. So what am I doing wrong?

  • You are missing the conditions for "must have 1 number, 1 lowercase, 1 upper case 1 special)" - you could model that with lookaheads. Look at https://docs.python.org/2/library/re.html for `(?=...)` - you probably need smth like "(?=[A-Z])(?=[a-z])(?=[0-9])(?=[@#$%^&+=])[A-Za-z0-9@#$%^&+=]*} – Patrick Artner Nov 10 '17 at 16:34
  • 1
    Probably this can help you: https://stackoverflow.com/questions/1559751/regex-to-make-sure-that-the-string-contains-at-least-one-lower-case-char-upper – Georgy Nov 10 '17 at 16:36
  • You can also check out [Django Regex Validator](https://docs.djangoproject.com/en/1.11/ref/validators/#regexvalidator) – Sheshnath Nov 10 '17 at 16:39

1 Answers1

3
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@#$%^&+=]).{8,25}$

You can try this.Each condition is added using lookahead.Add more special characters if you want.

See demo.

vks
  • 67,027
  • 10
  • 91
  • 124