在 SmartGwt 中创建一个验证器来检查 String 是否是一个 Integer
Create a validator in SmartGwt to check if String is an Integer
我有一个 TextItem
,我想在上面设置一个 Validator
,以便它检查输入是否为整数。
TextItem textItem = new TextItem();
textItem.setValidator(myValidator)
我应该如何创建我的 myValidator
来检查这个?我有:
myValidatorcv = new CustomValidator() {
@Override
protected boolean condition(Object value) {
if (Integer.parseInt(value);){
return true;
}else
return false;
}
}
};
这是最好的方法吗?我还需要在验证器中捕获数字格式异常吗?
Is that the best way to do this?
可能吧。任何时候您都可以利用框架的内置功能,这通常是一个好的解决方案的标志。
有些人可能会说异常驱动编程不是最好的方法,因为处理它们的成本很高,但这取决于您。
Also do I also need to catch the number format exception inside the validator?
是的,这就是您知道它是否失败的方式。
myValidatorcv = new CustomValidator() {
@Override
protected boolean condition(Object value) {
try {
Integer.parseInt(value.toString());
return true;
} catch (NumberFormatException) {
return false;
}
}
};
我不是很熟悉这个框架,但是如果你可以利用泛型来确保你正在验证的对象是 Integer
或 String
而不是 Object
, 这样就更好了
只需使用 IntegerRangeValidator。
我有一个 TextItem
,我想在上面设置一个 Validator
,以便它检查输入是否为整数。
TextItem textItem = new TextItem();
textItem.setValidator(myValidator)
我应该如何创建我的 myValidator
来检查这个?我有:
myValidatorcv = new CustomValidator() {
@Override
protected boolean condition(Object value) {
if (Integer.parseInt(value);){
return true;
}else
return false;
}
}
};
这是最好的方法吗?我还需要在验证器中捕获数字格式异常吗?
Is that the best way to do this?
可能吧。任何时候您都可以利用框架的内置功能,这通常是一个好的解决方案的标志。 有些人可能会说异常驱动编程不是最好的方法,因为处理它们的成本很高,但这取决于您。
Also do I also need to catch the number format exception inside the validator?
是的,这就是您知道它是否失败的方式。
myValidatorcv = new CustomValidator() {
@Override
protected boolean condition(Object value) {
try {
Integer.parseInt(value.toString());
return true;
} catch (NumberFormatException) {
return false;
}
}
};
我不是很熟悉这个框架,但是如果你可以利用泛型来确保你正在验证的对象是 Integer
或 String
而不是 Object
, 这样就更好了
只需使用 IntegerRangeValidator。