问题描述
我需要检查用户是否至少13岁。
问题是从PickerComponent赋予其Validator的对象是字符串,而不是日期(正如我预期的那样)。
该字符串是根据我的语言环境(在Simulator中)格式化的,因此对于 2003年5月9日,我得到的字符串是 09/05/03(令我惊讶的是,只显示了年份
I need to check if the user is at least 13 years old.The problem is that the object given from PickerComponent to its Validator is a String, instead of a Date (as I expected).That String is formatted according to my locale (in the Simulator), so for the "May 9, 2003" I get the String "09/05/03" (I'm also surprised that the year is indicated only by two digits instead of four).
所以...我尝试了以下代码,但是(在我的语言环境中)它不起作用。我需要一个适用于Date PickerComponent的验证器(它也与语言环境无关):
So... I tried the following code, but it doesn't work (in my locale). I need a working Validator for a Date PickerComponent (that it's also independent from the locale):
PickerComponent date = PickerComponent.createDate(new Date()).label("Data di nascita").errorMessage("Hai almeno 13 anni?");
Validator validator = new Validator();
validator.addConstraint(date, new Constraint() {
@Override
public boolean isValid(Object value) {
boolean res = false;
if (value instanceof String) {
String inputDate = (String) value;
Log.p("-----------------");
Log.p("Inserted birthday date: " + inputDate);
Log.p("-----------------");
try {
Calendar birthday = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/mm/yy");
birthday.setTime(simpleDateFormat.parse(inputDate));
Calendar nowLess13years = Calendar.getInstance();
nowLess13years.setTime(new Date());
nowLess13years.add(Calendar.YEAR, -13);
if (birthday.before(nowLess13years) || birthday.equals(nowLess13years)) {
res = true;
}
} catch (ParseException ex) {
Log.p("Cannot parse the date");
}
}
return res;
}
@Override
public String getDefaultFailMessage() {
return "You must be at least 13 years old";
}
});
推荐答案
在选择器代码中这确实是一个愚蠢的错误:
That was a really stupid bug in the picker code:
if(cmp instanceof Picker) {
((Picker)cmp).getValue();
}
而不是:
if(cmp instanceof Picker) {
return ((Picker)cmp).getValue();
}
明天将修复...
这篇关于代号一-addConstraint到PickerComponent日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!