栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring + Thymeleaf自定义验证显示

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring + Thymeleaf自定义验证显示

这可能是因为您的@PasswordsEqualConstraint被分配给整个bean(类型)而不是字段“
/confirm/iPassword”。要将可能违反约束的条件添加到具体字段,您可以像以下示例一样进行操作。

如果两个字段不相等,则FieldMatch比较两个字段,然后将验证错误分配给第二个字段。

顺便说一句。这是您正在做的事情的更通用的解决方案。密码示例,您可以像这样使用它

@FieldMatch(first = "password", second = "/confirm/iPassword", message = "Passowords are not equal.")

验证器:

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {  private String firstFieldName;  private String secondFieldName;  @Override  public void initialize(final FieldMatch constraintAnnotation) {    firstFieldName = constraintAnnotation.first();    secondFieldName = constraintAnnotation.second();  }  @Override  public boolean isValid(final Object value, final ConstraintValidatorContext context) {    try {      final Object firstObj = BeanUtils.getProperty(value, firstFieldName);      final Object secondObj = BeanUtils.getProperty(value, secondFieldName);      boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);      if (!isValid) {        context.disableDefaultConstraintViolation();        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addNode(secondFieldName).addConstraintViolation();      }      return isValid;    }    catch (final Exception ignore) {      // ignore    }    return true;  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421915.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号