When i do a POST request to /register with user with null email, i expect it to say something "hey, you have null in email field", but it throws NPE on saving step because of user.email!!
statement.
When i send json with wrong email like this:
{
"email": "wrongEmailAddress",
"username": "username",
"phoneNumber": "+7 909 909 9009",
"password": "234adfg24",
"role": "USER"
}
it perfectly passes through this constraint annotation:
@Email
@Pattern(regexp = ".+@.+\\..+", message = "Please provide a valid email address")
@Target(
AnnotationTarget.FIELD,
AnnotationTarget.FUNCTION,
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.PROPERTY,
AnnotationTarget.PROPERTY_GETTER)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [])
@MustBeDocumented
annotation class ValidEmail(
val message: String = "Please provide a valid email address",
val groups: Array<KClass<out Any>> = [],
val payload: Array<KClass<out Payload>> = []
)
Why does not validation work?
Controller class:
@RestController
class UserController(
@Autowired val userService: UserService) {
@PostMapping(
path=["/register"],
consumes=["application/json"],
produces=["application/json"])
fun registerNewUser(
@Valid @RequestBody user: User): UserDTO {
user.encryptPassword()
userService.registerNewUser(user)
return UserDTO(user)
}
}
User class:
@Entity
class User(
@get:NotNull @field:ValidEmail @Column(unique = true)
var email: String? = null,
@get:NotNull @Column(unique = true)
var username: String? = null,
@get:NotNull @field:ValidPhoneNumber @Column(unique = true)
var phoneNumber: String? = null,
@get:NotNull @field:ValidPassword
var password: String? = null,
@get:NotNull
var role: Role? = null,
var address: String? = null
) : BaseEntity()
{
fun encryptPassword() {
password = BCryptPasswordEncoder().encode(password)
}
}
@MappedSuperclass
open class BaseEntity(
@Id @NotNull @GeneratedValue(generator = "UUID")
@GenericGenerator(name="UUID", strategy = "org.hibernate.id.UUIDGenerator")
open val id: UUID? = null)
What i tried. I tried to change between @ValidEmail, @get:ValidEmail, @field:ValidEmail ( kotlin data class + bean validation jsr 303 , https://stackoverrun.com/ru/q/9883168 and other sources), tried to rewrite everything in java. Nothing works. PhoneNumberValidator passes all unit tests, but the constraint @ValidPhoneNumber does not work too. Not even one constraint work. Thanks for any suggestions.