I am using @valid annotation for all the validations in spring mvc project. I want to validate phone number but I can't find a way.
I tried this, but gives error that I can't use @size on int/long.
@Size(10)
private long phone;
I also tried this but gives error on max value is out of bound as it can only take values in int.
@Min(1000000000)
@Max(9999999999)
private long phone;
I also tried regex in pattern but gives same error that I can't validate @pattern on int/long.
@Pattern(regex="...")
private long phone;
If I don't write any annotation and try to enter empty string, it gives error converting from string to long for empty string "". Is there any way I can validate phone number without changing it to string?
Edit : Yes, I have used @valid and Binding result and I cannot change phone to string as it is connected with database with having "bigint" in table and changing it here will affect everything else because I'm using Hibernate for auto saving in sql.
CodePudding user response:
You need to use String and @Valid
annotation with regex pattern.
CodePudding user response:
Insted of long
use String
datatype for phone number.
@Pattern(regexp = "...")
@Size(min=10,max=10)
private String phone;
For perform validation in Spring MVC, You have to put @Valid
annotaion and BindingResult
Interface in your controller. Here down is example
@Valid: Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph.
BindingResult: BindingResult is Spring object that holds the result of the validation and binding and contains errors that may have occurred.
@RequestMapping(value = "/url", method = RequestMethod.POST)
public String someMethod(@Valid Entity entity, BindingResult bindingResult)
{
if(bindingResult.hasErrors())
{
// if validation error is occured
System.out.println(bindingResult);
return "go_to_the_same_page";
}
return "page_name_where_you_wanna_go";
}