自定义表单验证注释无效

时间:2016-11-18 00:39:15

标签: java spring spring-mvc annotations bean-validation

我创建了一个自定义表单验证注释,以检查表单中填写的日期是否采用dd / MM / yyyy格式。不幸的是,它不起作用,验证失败,我尝试任何日期格式。最初我认为问题是我用于测试的正则表达式,但在做了一些测试后我很确定它有效。

我错过了什么?这是我的代码(我只复制相关部分),请帮助我理解我做错了什么:

bean Articolo(N.B:此类嵌套在下面的模型类NewEditArticle中)

@Entity
@Table (name="Articolo")
public class Articolo {

    @Column (name="Data")
    @Temporal (TemporalType.DATE) //match the data type used in DB
    @IsValidDate //check date format is dd/MM/yyyy (custom validator)
    private Date data;

类IsValidDate

@Documented //mandatory
@Constraint (validatedBy= DateValidator.class) //this class contains the validation logic
@Retention (RetentionPolicy.RUNTIME) //mandatory
public @interface IsValidDate {

    //error message
    String message() default "Please insert date in format dd/mm/yyyy";

    Class <?>[] groups() default {}; //mandatory

    Class <? extends Payload> [] payload () default {}; //mandatory
}

class DateValidator

public class DateValidator implements ConstraintValidator <IsValidDate, Date > {

    @Override
    public void initialize(IsValidDate isValidDate) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean isValid(Date data, ConstraintValidatorContext ctx) {

        //convert Date data to String
        String dateString=data.toString();

        //format dd/MM/yyyy
        String regex="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";


        if (dateString.matches(regex)){
            return true;
        }

        //if date doesn't match regex, return error message from IsValidDate
        else {
            return false;
        }
    }

}

模型类

public class NewEditArticolo {

    //ATTRIBUTES

    @Valid  //requested to trigger validation of bean Articolo
    private Articolo articolo;

    private List<Area> ListaArea;
    private List<Cucina> ListaCucina;
    private List<Prezzo> ListaPrezzo;
    private List<Voto> ListaVoto;
    private List<String> ListaImg;


    //METHODS

    //CONSTRUCTOR

    //create article model without ID number
    //used in controller POST method
    public NewEditArticolo () {

        populateLists();
    }

    //create Article model based on ID number
    //if ID=0 (new Article), creates empty model
    //used in controller GET method
    public NewEditArticolo(int ID) throws SQLException {

        // call DAOArticolo.select only if article already exists
        if (ID != 0) {
            DAOArticolo DAOart = new DAOArticolo();
            articolo = DAOart.select(ID);
        }

        populateLists();

    }

控制器

public String editArticle ( Model model,
                                @Valid @ModelAttribute (value="nea") NewEditArticolo nea, //create NewEditArticolo object, autowire attributes from ArticleManager.jsp, add to model and validate
                                BindingResult result, //collect validation errors
                                @RequestParam (value="submit") String submit){ //get input value from ArticleManager.jsp

        Articolo articolo1=nea.getArticolo();

        DAOArticolo daoArt = new DAOArticolo();

        //if validation fails, return form to display validation errors
        if (result.hasErrors()) {
            System.out.println("VALIDATION FAILED");
            return "ArticleManager";
        }

        else {
            System.out.println("VALIDATION WAS SUCCESFULL");
        }

弹簧调度-servlet.xml中

<bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages" />
    </bean>

1 个答案:

答案 0 :(得分:0)

没有正则表达式,你可以做到这一点。 Spring有@DateTimeFormat注释。在您的模型中执行以下操作。

@NotNull(message = "Please enter Birth Date")
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date birthDate;

您可以添加自定义错误消息。在资源文件夹下创建message.properties。在这个文件里面:

typeMismatch=Invalid date format

重点是将其添加到配置类中。

@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    return messageSource;
}