gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:44:04 27 4
gpt4 key购买 nike

我创建了一个自定义表单验证注释,以检查表单中填写的日期是否采用 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
}

类日期 validator

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();

}

Controller

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>

最佳答案

无需正则表达式即可做到这一点。 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;
}

关于java - 自定义表单验证注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40667562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com