Search code examples
javavalidationresthibernate-validatorspring-rest

How can i pass required parameters without violating validations for other input fields


I have created an input passing parameter class for all parameters of an module, & wants to use different parameters for different operations

My passing parameter class have fields as

private Integer userId;
@Id
@Column(name = "user_email_id")
@NotEmpty(message = "Please enter your email_Id.")
@Email
@NotNull(message = "Enter last name")
private String userEmailId;
@NotEmpty(message = "Please enter your password.")
@Column(name = "user_password")
private String userPassword;
@NotNull(message = "Enter last name")
@NotEmpty(message = "Please enter your firstName.")
@Column(name = "firstname")
@SafeHtml()
private String firstName;
@SafeHtml()
@NotNull(message = "Enter last name")
@NotEmpty(message = "Please enter your lastName.")
@Column(name = "lastname")
private String lastName;
@NotEmpty
@Pattern(regexp = "(^[0-9]{10,12}$)", message = "Please enter your Mobile Number.")
@NumberFormat
@Column(name = "mobile_number")
private String mobileNumber;
@Column(name = "user_status")
private Integer userStatus;
@Column(name = "isdeleted")
private Integer isDeleted;
@Column(name = "createdUserId")
private Integer createdUserId;
@Column(name = "profile_picturename")
private String profilePicturename;
@Column(name = "address")
private String address;

private Integer isAdmin;

here for registration i'm using

 {  
"userEmailId": "sdfdfgfgf",
"userPassword": "fdsdsdf",
"firstName": "sdfsdf",
"lastName": "sfdsdfds",
"mobileNumber": "sdfgdgdf",
"userStatus": 1,
"isDeleted": 0,
"createdUserId": 1,
"profilePictureName": "kfksdjfhksjd",
"address": "sfdsdfsd"

}

to pass parameters in json & for login trying to pass

{
"userEmailId": "f@g.cm",
"userPassword": "fdsdsdf",
"isAdmin":0

}

parameters , but for login i'm getting validation message of other fields as well,

can anyone tell me how can i pass only needed fields to the method without getting validation message for the fields that i'm not passing

Thnaks in advance


Solution

  • I am not so sure whether it makes so much sense to just group all potential parameters into a single class, but if you are saying that you only want to validate a given subset based on a specific usecase, you need to work with validation groups. Check the Hibernate Validator online docs for this feature. You basically assign the different constraints to distinctive groups, eg Login. When you then call Validator#validate you also pass the group you want to validate. If you control validation yourself that is not a problem. If you are using some other framework which in turn integrates with Bean Validation, you will need to check there how to validation for a given group.