Spring中的唯一列验证器

时间:2013-08-09 18:55:27

标签: java spring unique validation

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

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

    }

我想验证标题。

1 个答案:

答案 0 :(得分: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.");
        }

    }
}