ripper234
ripper234

Reputation: 230108

Can Validation be used with parameters that are enhanced in the controller?

I have a Website model, that has a @Required User owner property. This property gets filled inside the controller method. However, validation is checked upon entering the controller method, so it considers the object invalid (because at the time, it is).

Should Play! validation be used for this purpose?

Should I just drop the @Valid annotation and check manually using validation.required(website)?

Update - using validation.required(website) only validates that the website is not null, but it does not run validate any of the annotations on the website. If I'm not using the @Valid parameter annotation, does this mean I can't use annotation-based validations on the model itself? What's a programmer to do?

Update2 - it seems I should be calling validation.valid(website) instead of validation.required(website). I also added a @Required annotation to the add() method parameter (instead of @Valid). Is this the way it should be done?

@Entity
public class Website extends PortalModel {
    @Required
    public String url;

    @Required
    @ManyToOne
    public User owner;
}

public class Sites extends UserAwareControllerBase {
    public static void added(@Valid Website website) {
        website.owner = getUser(); // from base class

        if (Validation.hasErrors()) {
            Validation.keep();
            params.flash();
            add();
        }

        websiteRepo.save(website);
        edit(website.id);
    }
}

Upvotes: 1

Views: 296

Answers (1)

Marius Soutier
Marius Soutier

Reputation: 11274

I'm not sure if there's a point to declare User as @Required if your app's users have no influence on it. Well, it's a safety net for your own code.

But since the user is not in the parameters when you submit the website form, you have to validate manually:

website.owner = getUser();
validation.valid(website);
...

Upvotes: 1

Related Questions