一.前端校验(jquery.validate.min.js)
register.html
<form action="#" id="r-form">
<h1>注册</h1>
<input id="r-username" name="username" type="text" placeholder="昵称">
<input id="r-email" name="email" type="email" placeholder="电子邮箱">
<input id="r-password" name="password" type="password" placeholder="密码">
<button id="btn-register">注册</button>
</form>
register.js
$("#btn-register").click(function () {
$("#r-form").validate({ //调用validate方法开始校验,通过参数来进行具体校验的设置
submitHandler: function () {
$.ajax({
url: "/api/register",
type: "POST",
data: {
username: $("#r-username").val(),
email: $("#r-email").val(),
password: $("#r-password").val(),
},
success: function (result) {
}
});
return false; //注意当注册的<button></button>未指定type时表单会默认提交,所以这里要return false;
},
rules: { //指定校验规则
username: {
required: true,
minlength: 4,
maxlength: 12,
usernameCheck: true, //usernameCheck为自己制定校验规则的一个函数
},
email: {
required: true,
email: true,
},
password: {
required: true
}
},
messages: { //指定校验没通过后返回的信息
username: {
required: "昵称不能为空",
minlength: "昵称不能低于4个字符",
maxlength: "昵称不能超过12个字符",
},
email: {
required: "邮箱不能为空",
email: "邮箱格式不正确"
},
password: {
required: "密码不能为空",
}
},
});
});
自己制定校验规则的函数
jQuery.validator.addMethod("usernameCheck", function (value, element) {
var regExpStr = /^[\u4E00-\u9FA5A-Za-z0-9]+$/;
return regExpStr.test(value);
}, "昵称只支持中文、英文、数字");
效果:
二.后端校验(jsr303)
jsr303
:JSR是Java Specification Requests的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准.
百度百科上是这么解释jsr303的,通俗易懂的理解也就是它只是一个规范而已,使用我们实际上用的还是实现了这个规范的
hibernate-validator
1.在pom文件中导入对应的依赖
<!--JSR303-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
2.在需要校验的实体类上添加相关校验规则与校验失败返回信息
public class User implements Serializable {
private Integer id;
@NotBlank(message = Constant.REGISTER_USER_USERNAME_NULL)
@Length(min = 4, max = 12, message = Constant.REGISTER_USER_USERNAME_LENGTH)
@Pattern(regexp = "^[\\u4E00-\\u9FA5A-Za-z0-9]+$", message = Constant.REGISTER_USER_USERNAME_SUPPORT)
private String username;
@NotBlank(message = Constant.REGISTER_USER_PASSWORD_NULL)
private String password;
private String salt;
private Integer age;
private Integer gender;
@NotBlank(message = Constant.REGISTER_USER_EMAIL_NULL)
@Email(message = Constant.REGISTER_USER_EMAIL_FORMAT)
private String email;
}
3.在需要校验的实体类前加上@Valid
注解,被校验的类后面必须是BindResult
,不然会报错
@PostMapping(Api.REGISTER)
public Result register(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError error : allErrors) {
return Result.failure(Constant.REGISTER_USER_FORMAT_ERROR_CODE,
error.getDefaultMessage()); //defaultMessage为我们在我们上面message对应的值
}
}