Jun-11-2024, 05:28 PM
You should not be using multiple validators like that. Write a validator function for password and do all the validation using normal Python code.
This looks terrible:
This looks terrible:
np = PasswordField('New Password', [InputRequired(message='please enter your new password'), EqualTo('cnp', message='must match confirm new password'), Length(min=12), Regexp('.*[a-z]', message='must contain one lower case'), Regexp('.*[A-Z]', message='must contain one upper case'), Regexp('.*[0-9]', message='must contain one number'), Regexp('.*[\¬\!\"\£\$\%\^\&\*\(\)\_\+\`\-\=\{\}\:\@\~\<\>\?\[\]\;\'\#\,\.\/\\\|]', message='must contain one special character')])You it up quite a bit.
new_password = PasswordField('New Password', [ InputRequired(message='please enter your new password'), EqualTo('cnp', message='must match confirm new password'), Length(min=12), Regexp('.*[a-z]', message='must contain one lower case'), Regexp('.*[A-Z]', message='must contain one upper case'), Regexp('.*[0-9]', message='must contain one number'), Regexp('.*[\¬\!\"\£\$\%\^\&\*\(\)\_\+\`\-\=\{\}\:\@\~\<\>\?\[\]\;\'\#\,\.\/\\\|]', message='must contain one special character')] )Or better yet, write a validator function.
class PasswordForm(FlaskForm): username = StringField('Username', [InputRequired(message='please enter your Username')]) old_password = PasswordField('Current Password', [InputRequired(message='please enter your current password')]) new_password = PasswordField('New Password', [InputRequired(message='please enter your new password')]) confirm_password = PasswordField('Confirm New Password') def validate_new_password(form, field): """Validate password field.""" if field.data == form.old_password.data: raise ValidationError('new password cannot be the same as current password.') if field.data != form.confirm_password.data: raise ValidationError('passwords do not match.') if len(field.data < 12): raise ValidationError('must be at least 12 characters long') if re.match(r"[A-Z]", field.data) is None: raise ValidationError('must contain an upper case letter.') if re.match(r"[a-z]", field.data) is None: raise ValidationError('must contain a lower case letter.') if re.match(r"[0-9]", field.data) is None: raise ValidationError('must contain a digit.') if re.match(r"[\¬\!\"\£\$\%\^\&\*\(\)\_\+\`\-\=\{\}\:\@\~\<\>\?\[\]\;\'\#\,\.\/\\\|]", field.data) is None: raise ValidationError('must contain a special character.') if form.username.data is not None: if field.data in form.username.data.split(): raise ValidationError('cannot be your first or last name.')Beware, untested code.