验证JavaFX中的空白字段

时间:2013-06-20 12:07:28

标签: java mysql validation javafx

我在尝试在数据库中插入数据之前验证空白字段时遇到问题。我目前正在使用Netbeans JavaFX应用程序,场景构建器和MySQL。

对于此方法,它会将面板内的组件传递给控制器​​类。

private void createProduct(ActionEvent event){
CreateProductController controller = new CreateProductController();
boolean result = controller.create(myPane);
if(result)
{
    System.out.println("Success");
}
}

在我的控制器类中,我得到了一个validateDetails方法,它在插入和创建方法之前检查空白字段。

public boolean create(CreateProductUI panel){
    String name = panel.getNameTextField().getText();
    //And the rest of the components which I removed before it's very long

    //I used if else statement to check 
    boolean invalid = true;
    if(invalid){
        validateDetails(name,desc,priceStr,qtyStr,dateStr,image,category);
        return invalid;
    }else{
    invalid = false;
    Product product1 = new Product(name,desc,price,quantity,dateStr,image,category);
    product1.create();
    return invalid;
    }
}

这是我的验证方法:

  public void validateDetails(String name,String desc,String priceStr,String qtyStr,String dateStr,Image image,int category){
    if(name.equals("")){
        JOptionPane.showMessageDialog(null,"Please enter name");       
    }else if(desc.equals("")){
        JOptionPane.showMessageDialog(null,"Please enter description");
    }else if(priceStr.equals("")){
        JOptionPane.showMessageDialog(null,"Please enter price");
    }else if(qtyStr.equals("")){
        JOptionPane.showMessageDialog(null,"Please enter quantity");
    }else if(category <= -1){
        JOptionPane.showMessageDialog(null,"Please choose category");
    }
}

但是,当检测到任何空白字段时,程序不会执行以提示错误消息。例如,我将2个字段留空。它应该提示两次。相反,它只是添加到我的数据库表。

提前致谢。

2 个答案:

答案 0 :(得分:0)

将您的方法更改为:

public boolean create(CreateProductUI panel){
 String name = panel.getNameTextField().getText();
 //And the rest of the components which I removed before it's very long

 //I used if else statement to check 
 boolean valid = validateDetails(name,desc,priceStr,qtyStr,dateStr,image,category);

 if(valid) {
     Product product1 = new Product(name,desc,price,quantity,dateStr,image,category);
     product1.create();
 }

 return valid;
 }
}



public boolean validateDetails(String name,String desc,String priceStr,String qtyStr,String dateStr,Image image,int category){

 StringBuilder sb = new StringBuilder();
 if(name.equals("")){
    sb.append(" name ");
 }
 if(desc.equals("")){
    sb.append(" desc ");     
 }
 if(priceStr.equals("")){
    sb.append(" Price "); 
 }
 if(qtyStr.equals("")){
   sb.append(" Quantity ");     
 }
 if(category <= -1){
sb.append(" Category ");    
 }
 String message = sb.toString();
 if(message.length() > 0) {
   JOptionPane.showMessageDialog(null,"Please fill up these values: "+message);
   return false;
 }
 return true;
} 

答案 1 :(得分:0)

而不是仅使用else if使用'if条件。因为在您的情况下,如果名称字段不为空,则不会检查第二个条件。