如何评估表单中日期字段是否正确填写



Context
我有一个表单(使用Java和GWT开发(,它有两个字段(起始日期和最终日期(,我想在将数据发送到服务器之前对它们进行评估。

预期
如果两个字段中的一个没有设置,我会收到错误消息

观察到
由于无法从空值中获取字符串,因此在编译过程中我在代码中遇到错误

代码:

Date beginValue = this.beginDateObj.getMyValue();
Date endValue = this.endDateObj.getMyValue();

if (((beginValue == null || beginValue.toString().isEmpty()) && ((endValue != null || !endValue.toString().isEmpty()))) ||
((beginValue != null || !beginValue.toString().isEmpty()) && ((endValue == null || endValue.toString().isEmpty())))) {
myError.setText(constants.mandatoryFieldCombined2());
myError.setVisible(true);
isValid = false;
}

我不知道那个代码中有什么不正确的地方。我一直认为空比较是代码评估的第一件事,如果它是真的,就没有必要评估其余的比较,不是吗?

感谢

这就是问题所在:

(endValue != null || !endValue.toString().isEmpty())

如果endValue为null,则将计算endValue.toString((。

你想要这个:

(endValue != null && !endValue.toString().isEmpty())

或逻辑等价物:

(!(endValue == null || endValue.toString().isEmpty()))

你也在用beginValue做类似的事情,这需要类似的修正。

相关内容

最新更新