Robin
Robin

Reputation: 3850

Spring Email Form Validation

I am about to setup form validation in Spring 3.1. I am using Annotations to validate my Model, like this:

Model:

@Column(name = "mailAddress", nullable = false)
@Email
private String mailAddress;

@Column(name = "school", nullable = false)
@NotBlank
@Size(min = 3, max = 100)
private String school;

Controller:

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addBooking(
            @ModelAttribute("new-booking") @Valid Booking booking,
            BindingResult result, Map<String, Object> model) {

        if (result.hasErrors()) {
            return "booking";
        }
            return "success";
     }

The Problem is, it validates the school but not the mailAddress. If you enter an empty mailAddress it will accept it.

Upvotes: 1

Views: 9576

Answers (2)

Robin
Robin

Reputation: 3850

I found the Issue. The Email Validator will accept Blank Emails. To fix this you only need to add a @NotBlank to it. Actually I thought the nullable = false would be enought, but wasn't.

@Column(name = "mailAddress", nullable = false)
@Email
@NotBlank
private String mailAddress;

Upvotes: 4

AndreaNobili
AndreaNobili

Reputation: 42997

I think that maybe your validation problem could be related to the fact that using @Email validation annotation your validator cosindered as valid also e-mail having form like: "myname@service" that don't end with an extension like (for example) .com

If this is your problem...this is normal because it considered also the case that you have an e-mail having the following format: yourname@localhost (internal email address)

If you would validate a classic e-mail (having format: [email protected]) I think that you have to write your custom validator.

I hope that I have understand your problem

Upvotes: 4

Related Questions