ComboBox的Hibernate验证器

时间:2016-03-29 05:47:08

标签: java hibernate validation hibernate-validator

如何验证jComboBox以供用户选择除默认项目以外的任何项目?

我需要检查用户是否没有选择任何项目。所以jComboBox值将是“请选择一个成熟度问题”

enter image description here

在我的模型课中,

@NotEmpty(message="Please fill the username field!")
public String getUsername() {
    return this.username;
}

public void setUsername(String username) {
    this.username = username;
}

@NotEmpty(message="Please fill the password field!")
public String getPassword() {
    return this.password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getSeqQue() {
    return this.seqQue;
}

public void setSeqQue(String seqQue) {
    this.seqQue = seqQue;
}

在getSeqQue()中添加hibernate验证器注释以验证我的jComboBox是什么?

1 个答案:

答案 0 :(得分:1)

  

要使用自定义消息验证您的JComboBox,您只需制作自定义约束验证器。

参见以下示例:

<强> MyModel.java

public class MyModel {

    @ValidComboBox //this is the annotation which validates your combo box
    private String question;

    //getter and setter
}

ValidComboBox.java //注释

import java.lang.annotation.*;
import javax.validation.*;

@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ComboBoxValidator.class)
@Documented
public @interface ValidComboBox {
String value = "Please select a security question";

String message() default "Please select a security question.";

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

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

<强> ComboBoxValidator.java

import javax.validation.*;
public class ComboBoxValidator implements ConstraintValidator<ValidComboBox, String> {

private String value;

@Override
public void initialize(ValidComboBox arg0) {
    this.value = arg0.value;

}

@Override
public boolean isValid(String question, ConstraintValidatorContext arg1) {
    if(question.equalsIgnoreCase(value)){
        return false;
    }
    return true;
}
}

将项目添加到jComboBox,如下所示:

JComboBox<String> jComboBox = new JComboBox<>();
jComboBox.addItem("Please select a scurity question");
jComboBox.addItem("Question 1");
jComboBox.addItem("Question 2");

以下行需要在执行验证操作时添加:

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();

String question = jComboBox.getSelectedItem().toString();
MyModel model = new MyModel();
model.setQuestion(model);

Set<ConstraintViolation<MyModel>> constraintViolations = validator.validate(model);

if (!constraintViolations.isEmpty()) {
        String error = "";
        for (ConstraintViolation<MyModel> constraintViolation : constraintViolations) {
                error += constraintViolation.getMessage();
                JOptionPane.showMessageDialog(null, error);
        }
}
  

如果您尝试在不选择问题的情况下发送请求,则会显示请选择安全问题消息。