Codename One - addConstraint to PickerComponent date

做~自己de王妃 提交于 2019-12-08 06:09:19

问题


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).

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";
            }
        });

回答1:


That was a really stupid bug in the picker code:

    if(cmp instanceof Picker) {
        ((Picker)cmp).getValue();
    }

Instead of:

    if(cmp instanceof Picker) {
        return ((Picker)cmp).getValue();
    }

Will be fixed tomorrow...



来源:https://stackoverflow.com/questions/50249148/codename-one-addconstraint-to-pickercomponent-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!