2

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>> = []
)

request screenshot

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.

alyssa moon
  • 35
  • 1
  • 7

1 Answers1

4

Mark your restcontroller with @Validated.

Daniel Jacob
  • 1,455
  • 9
  • 17
  • it does not work. this annotation is used to allow validating request parameters and path variables ( https://reflectoring.io/bean-validation-with-spring-boot/ ) i have another java project with bean validation where everything works properly without @Validated – alyssa moon Aug 14 '20 at 02:05
  • did you try to add rhe @Valid annotation on the property? – Daniel Jacob Aug 14 '20 at 05:39
  • if you mean validation on request params and path vars like i mentioned, answer is no, but even @NotNull annotation on class property does not work – alyssa moon Aug 14 '20 at 05:54
  • What Spring boot version are you using? – Daniel Jacob Aug 14 '20 at 09:35
  • 2.3.2.RELEASE. Problem solved after i recreated project with gradle and everythink works now, used maven before. btw was it my fault or maven really such a bad thing? – alyssa moon Aug 14 '20 at 09:43
  • Perhaps you needed to do a mvn clean install. Also, I was going to say you needed to include spring-boot-starter-validation since in the newest versions this is not automatically packaged with spring boot anymore. – Daniel Jacob Aug 14 '20 at 09:46
  • i did clean and then install didnt work anymore, it was saying "symbol not found", before it worked ok, dont wanna deal with maven anymore – alyssa moon Aug 14 '20 at 09:50