填写表单时验证错误

时间:2016-10-20 10:08:57

标签: java spring spring-mvc thymeleaf

我正在尝试在错误输入传递时设置验证自定义错误。

这是我在百里香模板的帮助下写的表格:

<form th:action="@{/addPet}" th:object="${petDto}" method="post">
            <table>
                <tr>
                    <td>Pet name:</td>
                    <td><input type="text" th:field="*{pet.petName}" /></td>
                    <td th:if="${#fields.hasErrors('pet.petName')}" th:errors="*{pet.petName}">fieldError</td>
                </tr>
                <tr>
                    <td>Owner First name:</td>
                    <td><input type="text" th:field="*{owner.firstName}" /></td>
                    <td th:if="${#fields.hasErrors('owner.firstName')}" th:errors="*{owner.firstName}">fieldError</td>
                </tr>
                <tr>
                    <td>Owner Last name:</td>
                    <td><input type="text" th:field="*{owner.lastName}" /></td>
                    <td th:if="${#fields.hasErrors('owner.lastName')}" th:errors="*{owner.lastName">fieldError</td>
                </tr>
                <tr>
                    <td>Owner Number:</td>
                    <td><input type="text" th:field="*{owner.phoneNumber}" /></td>
                    <td th:if="${#fields.hasErrors('owner.phoneNumber')}" th:errors="*{owner.phoneNumber}">fieldError</td>
                </tr>
                <tr>
                    <td><input type="submit" value="add" /></td>
                </tr>
            </table>

因此传递dto包含两个字段:

public class PetDto {


    private Pet pet;
    private Owner owner;

现在,当我输入错误的输入时,我得到了这个:

here was an unexpected error (type=Internal Server Error, status=500).
Validation failed for classes [pl.kaczynski.model.Owner] during persist time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Length must be between 2 and 15 characters.', propertyPath=lastName, rootBeanClass=class pl.kaczynski.model.Owner, messageTemplate='{Size}'} ConstraintViolationImpl{interpolatedMessage='Length must be between 2 and 15 characters.', propertyPath=firstName, rootBeanClass=class pl.kaczynski.model.Owner, messageTemplate='{Size}'} ConstraintViolationImpl{interpolatedMessage='numeric value out of bounds (<9 digits>.<0 digits> expected)', propertyPath=phoneNumber, rootBeanClass=class pl.kaczynski.model.Owner, messageTemplate='{javax.validation.constraints.Digits.message}'} ]

我的目标是在同一视图中的输入字段旁边显示错误消息,而不是重定向到错误页面。我为对象Pet和Owner制作了类似的表单页面,并且它工作正常,这让我觉得我的作文类DTO存在问题。

编辑// 这是模型类:

@Entity
public class Pet extends BaseClass{

    @Column(name = "pet_name")
    @Size(min=2,max=15,message="{Size}")
    private String petName;
    @OneToOne()
    @JoinColumn(name = "owner_Id")
    private Owner owner;

@Entity
public class Owner extends BaseClass {

    @Column(name = "first_name")
    @Size(min = 2, max = 15, message = "{Size}")
    private String firstName;

    @Column(name = "last_name")
    @Size(min = 2, max = 15, message = "{Size}")
    private String lastName;

    @Column(name = "phone")
    @Digits(fraction = 0, integer = 9)
    private String phoneNumber;

这是控制器:

@RequestMapping(value = "/addPet", method = RequestMethod.POST)
    public String addPetPost(@Valid @ModelAttribute(value="petDto") PetDto petDto, BindingResult result){

        if(result.hasErrors())
            return "/addPet";

        Owner owner = petDto.getOwner();
        Pet pet = petDto.getPet();
        pet.setOwner(owner);

        ownerService.add(owner);
        petService.add(pet);
        return "redirect:addPet";
    }

1 个答案:

答案 0 :(得分:0)

尝试这种方法:

<tr>
    <td>Pet name:</td>
    <td><input type="text" th:field="*{pet.petName}" /></td>
    <span th:if="${#fields.hasErrors('pet.petName')}">
        <ul>
            <li th:each="err : ${#fields.errors('pet.firstName')}" th:text="${err}">error text</li>
        <ul>
    </span>
</tr>

如果您有相同字段的多条错误消息(例如需要名字名字必须包含2到15个字符等),它们将在列表。