I need password validation (for example a password must contain at least 4 chars, max 8 and min 1 numeric digit).I have model (of course with getters and setters):

 @Entitypublic class User implements Serializable{/*** */private static final long serialVersionUID=5534441879591858724L;@Id@GeneratedValueprivate long id;@NotBlank@Emailprivate String email;@Pattern(regexp="^(?=.*\\d).{4,8}$", flags=Flag.UNICODE_CASE)private String password;@NotBlank@Size(min=2, max=30)private String name;

I'm catching ConstraintViolationException during saving user info to database and use informations from this exception to inform the user during registration what fields must be corrected because of invalid length etc.

Everything is ok with validation, but not with password. I checked regex expression out of this model class and it works ok, but when i put this regex into annotation parameter ( @Pattern(regexp="^(?=.*\\d).{4,8}$", flags=Flag.UNICODE_CASE)) it doesn't work and I have an error:

HHH000346: Error during managed flush [Validation failed for classes[pl.rpf.kingdom.models.User] during persist time for groups[javax.validation.groups.Default, ] List of constraint violations:[ConstraintViolationImpl{interpolatedMessage='must match "^(?=.*\d).{4,8}$"', propertyPath=password, rootBeanClass=classpl.rpf.kingdom.models.User,messageTemplate='{javax.validation.constraints.Pattern.message}'} ]]

Please help me with understanding this error and maybe you have some idea how to solve this problem.

share|improve this question
  • You may benefit from reading Reference - Password Validation. I'm not sure why you're capping passwords between 4 and 8 characters...– ctwheelsFeb 14 at 19:49
  • Which password failed the check?– sp00mFeb 14 at 19:49
  • Ok. It's only example, regex is not so important now. If it will works with one correct regex i will find better regex for stronger password ;)– rbednarskaFeb 14 at 19:51
  • actualy p.ex pass123 will not work too (it has at least 4, max 8 chars, one number). But I tested it in other class with normal matches() method and it was ok. Only with my annotation it doesn't work.– rbednarskaFeb 14 at 19:54

Problem was with password encrypting, I forgot about it. Regex matches mathod was always false, because it was trying to compare password after encrypting. I solved problem by putting validation out of model class, before password encrypting. Other way to resolve problem could be using spring @Valid annotation to validate form before trying save it to database (in my situation it could be problematic from other cases).

share|improve this answer

    Your Answer

     
    discard

    By posting your answer, you agree to the privacy policy and terms of service.

    Not the answer you're looking for? Browse other questions tagged or ask your own question.