4. validator
在一些应用场景中,我们需要验证表格的各个组件的填写,比如说,必须填写的组件,必选组件,密码要求等等,都可以在validator中完成。
- JSF中可以用來调用后端的Validator方法,例如:
<!-- 在前端中 -->
<h:inputText id="username" placeholder="5-20个英语,字符,数字,区分大小写"
validator="#{UserController.userNameValidate}"></h:inputText>
// 后端的Bean中
public void userNameValidate(FacesContext context, UIComponent component, Object value)
throws IllegalStateException, SecurityException, HeuristicMixedException, HeuristicRollbackException,
RollbackException, SystemException {
if (value.toString().length() < 5 || value.toString().length() > 20) {
throw new ValidatorException(new FacesMessage("用户名长度应为5-20个字符"));
}
if (loginValidate1(value.toString())) {
throw new ValidatorException(new FacesMessage("该用户名已注册"));
}
}
————————————————
此部分代码来自于CSDN博主「高自强」的原创文章
原文链接:https://blog.csdn.net/qq_33429968/article/details/73928719
- 在primeface中的使用:调用某个继承了Validator类的子类的validate()方法。具体调用类通过validatorId=“validator_name”来实现。例如:
<!-- attribute可以添加想要传递的参数 -->
<f:validator validatorId="projectValidator" />
<f:attribute name="projectNo"
value="123456" />
// 通过注解来管理validator子集(类似Bean)
@FacesValidator("projectValidator")
public class ProjectValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null) {
// 通过从前端的组件中获得自己想要的参数
String reportNo = (String) component.getAttributes().get("reportNo");
String validationMessage = MessageUtils.getMessage("message.report.empty",reportRefNo);
FacesMessage msg = new FacesMessage(validationMessage);
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}