Sorry for asking the simple question. I searched a lot , but can't find the exact solution.
In my spring bean class I have int field like (private int id) . I used @NotEmpty
annotion.
I need to allow only numbers not any alphabets or string in the input field. What annotation I need to use.
I have tried the @NumberFormat(style = Style.NUMBER)
, @Digits(fraction = 0, integer = 5)
annotations and nothing working out.
Please suggest me the solution or any example for form validation...
I suggest you to read the relevant part of the reference carefully. You create your validator which implements the Validator interface:
public class FooValidator implements Validator {
/**
* This Validator validates *just* Foo instances
*/
public boolean supports(Class clazz) {
return Foo.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Foo foo = (Foo) obj;
if (!isNumeric(foo.getFieldThatShouldBeNumeric())
{
e.rejectValue("fieldThatShouldBeNumeric", "notnumeric");
}
}
}
then inject it, either 'locally' to the controller itself:
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { ... }
or 'globally':
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven validator="globalValidator"/>
</beans>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.