日期:2014-05-16 浏览次数:20478 次
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.1.0.Final</version> </dependency>
@NotEmpty private String userName; @Email private String email;
	@RequestMapping("/valid")
	public String valid(@ModelAttribute("vm") [color=red]@Valid[/color] ValidModel vm, BindingResult result) {
		if (result.hasErrors()) {
			return "validResult";
		}
		return "helloworld";
	}<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Reservation Form</title>
<style>
.error {
	color: #ff0000;
	font-weight: bold;
}
</style>
</head>
<body>
	<form:form method="post" modelAttribute="vm">
		<form:errors path="*" cssClass="error" />
		<table>
			<tr>
				<td>Name</td>
				<td><form:input path="userName" />
				</td>
				<td><form:errors path="userName" cssClass="error" />
				</td>
			</tr>
			<tr>
				<td>email</td>
				<td><form:input path="email" />
				</td>
				<td><form:errors path="email" cssClass="error" />
				</td>
			</tr>
	
			<tr>
				<td colspan="3"><input type="submit" />
				</td>
			</tr>
		</table>
	</form:form>
</body>
</html>
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = FixLengthImpl.class)
public @interface FixLength {
	int length();
	String message() default "{net.zhepu.web.valid.fixlength.message}";
	Class<?>[] groups() default {};
	Class<? extends Payload>[] payload() default {};
}public class FixLengthImpl implements ConstraintValidator<FixLength, String> {
	private int length;
	@Override
	public boolean isValid(String validStr,
			ConstraintValidatorContext constraintContext) {
		if (validStr.length() != length) {
			return false;
		} else {
			return true;
		}
	}
	@Override
	public void initialize(FixLength fixLen) {
		this.length = fixLen.length();
	}
}<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" p:fallbackToSystemLocale="true" p:useCodeAsDefaultMessage="false" p:defaultEncoding="UTF-8"> <description>Base message source to handle internationalization </description> <property name="basenames"> <list> <!-- main resources --> <value>classpath:valid/validation</value> </list> </property> </bean>
	<bean id="validator"
		class="org.springfra