I am working on Spring MVC project. I add some validation for Signup form fields. When i click on submit button in form, get validation exception in password field must match "^\$2[ayb]\$.{56}$"
. Problem is create, While encode password in bCryptPasswordEncoder
and this password does not match with pattern.
Maybe encoded password look like
$2y$15$nK/B6u765645/lo0867h56546v/BnH5U5g45Aj67u67nMVtrhryt6
. I reference to this question Regular expression to find bcrypt hash? for solve problem but can not worked or me.
Here down is code:
Entity
@Entity
@Table(name = "USER")
public class User {
...
...
...
@Pattern(regexp = "^\\$2[ayb]\\$.{56}$")
private String password;
}
Controller
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String resiterUser(@Valid @ModelAttribute("user") User user,
BindingResult result)
{
if(result.hasErrors())
{
System.out.println(result);
mdl.addAttribute("user", user);
return "signup";
}
// ------ Problem Create Here ------
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
userRepo.save(user);
return "redirect:/";
}
View
<form th:action="@{/register}" method="post" th:object="${user}">
<div >
<label for="form3Example4cg">Password</label>
<input type="password"
id="form3Example4cg"
th:classappend="${#fields.hasErrors('password') ? 'is-invalid' : ''}"
th:value="${user.password}"
name="password" />
<div id="validationServer04Name" th:each="e: ${#fields.errors('password')}" th:text=${e}>
</div>
</div>
<div >
<button type="submit" >Primary</button>
</div>
</form>
CodePudding user response:
There are two phases of validation - the MVC layer and the JPA layer. If you use the same model class for both layers then you can't use the same field for two different things.
You can separate them like this, for example:
@Entity
@Table(name = "USER")
public class User {
@Column(name = "password")
@Pattern(regexp = "^\\$2[aby]\\$.{56}$")
private String encodedPassword
// for form binding only
private transient String newPassword;
}
user.setEncodedPassword(bCryptPasswordEncoder.encode(user.getNewPassword()));