0

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

@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.");
        }

    }

我想验证标题。

4

1 回答 1

0

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

@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.");
        }

    }
}
于 2013-08-09T19:12:51.700 回答