繁体   English   中英

Spring中的唯一列验证器

[英]Unique column validator in Spring

我想添加验证器,如果值不是唯一的,它将返回错误。 这个怎么做? 这是我当前的验证器:

@Component
public class AddFormValidator implements Validator {
    public boolean supports(Class<?> clazz) {
        return AddForm.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        AddForm addForm = (AddForm) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title",
                "title.empty", "Title must not be empty.");
        String title = addForm.getTitle();
        if ((title.length()) > 30) {
            errors.rejectValue("title", "title.tooLong",
                    "Title must not more than 16 characters.");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "content",
                "content.empty", "Content must not be empty.");
        String content = addForm.getContent();
        if ((content.length()) > 10000) {
            errors.rejectValue("content", "content.tooLong",
                    "Content must not more than 10K characters.");
        }

    }

我想验证标题。

我不知道您如何进行数据库访问,您可能应该注入一个查询数据库的存储库,以检查标题是否已存在。 就像是 :

@Component
public class AddFormValidator implements Validator {

    @Autowired
    NewsRepository newsRepository;       

    public boolean supports(Class<?> clazz) {
        return AddForm.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        AddForm addForm = (AddForm) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title",
                "title.empty", "Title must not be empty.");
        String title = addForm.getTitle();
        if ((title.length()) > 30) {
            errors.rejectValue("title", "title.tooLong",
                    "Title must not more than 16 characters.");
        }

        New new = newsRepository.findByTitle(title);
        // New already exist
        if (new != null) {
            errors.rejectValue("title", "title.alreadyExist",
                    "New title already exist");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "content",
                "content.empty", "Content must not be empty.");
        String content = addForm.getContent();
        if ((content.length()) > 10000) {
            errors.rejectValue("content", "content.tooLong",
                    "Content must not more than 10K characters.");
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM