Gopal SA
Gopal SA

Reputation: 959

Play! 1.2.5 with mongodb | Model Validation not happening

I have a simple User model whose fields are annotated with play validation annotations and morphia annotations like below.

import play.data.validation.*;
import play.modules.morphia.Model;
import com.google.code.morphia.annotations.*;

@Entity
public class User extends Model{

    @Id
    @Indexed(name="USERID", unique=true)
    public ObjectId userId;

    @Required public String userName;


    @Email
    @Indexed(name="USEREMAIL", unique=true) 
    @Required public String userEmail;  
}

Now I have a service which has a CreateNewUser method responsible for persisting the data. I have used Morphia plugin for the dao support. But the problem is that User Document gets persisted in mongo-db even if userName or userEmail is NULL. Also @Email validation does not happen

// Below code is in app/controllers/Application.java
User a = new User();
a.userName = "user1";
// calling bean to create user, userService is in app/service/UserService
userService.createNewUser(a);

It does not work even after adding @valid and validation.hasErrors() check.Below code is in app/service/UserService

public void createNewUser(@Valid User user) {
        if (Validation.hasErrors()) {
              System.out.println("has errors");
            }   else {
            // TODO Auto-generated method stub
              userDao.save(user);
        }
}

Upvotes: 1

Views: 599

Answers (1)

Schleichardt
Schleichardt

Reputation: 7552

Now I understand, createNewUser is not an action. So you can enforce object validation:

public void createNewUser(User user) {
    final Validation.ValidationResult validationResult = validation.valid(user);
    if (validationResult.ok) {
        userDao.save(user);
    }   else {
        System.out.println("has errors");
    }
}

api: http://www.playframework.org/documentation/api/1.2.5/play/data/validation/Validation.html

Old answer

You forgot an annotation to validate the object and you must check if the form has errors.

public void createNewUser(@Valid User user) {
     if(validation.hasErrors()) ...

source: http://www.playframework.org/documentation/1.2.5/validation#objects

Upvotes: 1

Related Questions