title: How to use @Size validation contraint for passwords that are hashed automatically
body: <p>Im using Spring with Hibernate to interact with my database. I'm using JPA/Hibernate contraints to validate the input. But this doesn't seem to work for the passwords and I think it's because the <code>setPassword()</code> method of the <code>User</code> class automatically hashes the password. Here's some code:</p>
  
  <pre><code>class User {
  
      @Size(min = 12, max = 100)
      private String password;
  
      public User(..., String password) {
          this.passwordSeed = this.passwordSeed = DigestUtils.sha256Hex(random.generateSeed(32));
          this.password = DigestUtils.sha256Hex(password + this.passwordSeed);
      }
  
      public String getPassword() {
          return password;
      }
  
      public void setPassword(String password) {
          if (passwordSeed == null) {
              this.passwordSeed = DigestUtils.sha256Hex(random.generateSeed(32));
          }
          this.password = DigestUtils.sha256Hex(password + this.passwordSeed);
      }
  }
  </code></pre>
  
  <p>Note that I've trimmed the code a lot to be able to focus on the essential part. The <code>...</code> in the constructor is my way of saying it has many more arguments to set other properties like <code>firstName</code>, etc.</p>
  
  <p>So the problem is that the @Size constraint doesn't throw an exception when the user enters for example a one letter password. @Size does work for the firstName for example.</p>
  
  <p>I've tried adding the constraint to the method variable, but that doesn't work either. Like this:</p>
  
  <pre><code>class User {
  
  
      private String password;
  
      public User(..., @Size(min = 12, max = 100) String password) {
          this.passwordSeed = this.passwordSeed = DigestUtils.sha256Hex(random.generateSeed(32));
          this.password = DigestUtils.sha256Hex(password + this.passwordSeed);
      }
  
      public String getPassword() {
          return password;
      }
  
      public void setPassword(@Size(min = 12, max = 100) String password) {
          if (passwordSeed == null) {
              this.passwordSeed = DigestUtils.sha256Hex(random.generateSeed(32));
          }
          this.password = DigestUtils.sha256Hex(password + this.passwordSeed);
      }
  }
  </code></pre>
  
  <p>Note that outside of the model, no hashing or manipulation of the password is done.</p>
  
  <p>So how would I correctly approach this to have a simple validation that checks the minimum length of 12 characters and max of 100 ones?</p>