自定义表单验证注释不起作用



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

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

bean Articolo(注意:这个类嵌套在模型类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
}
类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");
        }

Spring-dispatcher-servlet.xml

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

不使用Regex也可以这样做。Spring有@DateTimeFormat注释。在您的模型中执行以下操作:

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

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

typeMismatch=Invalid date format

重要的是将它添加到配置类中。

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

最新更新