原本妄想繼承LazyValidatorForm來避免繼承ActionServlet,就不用動到web.xml設定達到Date型態通透性。結果是不可能,不過倒是玩了一下下日期在Regex的判斷:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegex {

    public static void main(String[] args) {
        Pattern pat = Pattern.compile("^(\\d{4})[\\/\\-](0?[1-9]|1[0-2])[\\/\\-]([012]\\d?|3[01]|[3-9]\\b)");
        String tests [] = {
               
"2010/4/29",
                "2010-4-29",

                "2010/13/29",
                "2010/4/32",
                "2010/04/06",
                "2010/24/06",
               
"2010/9/6",
                "2010/05/30 16:14:20",
                "2010/2/31",

        };

        Matcher mat;
        for (int i=0; i<tests.length; i++){
            mat = pat.matcher(tests[i]);
            System.out.print("input: "+tests[i]+" ");
            if (mat.find())
                System.out.println("matched with: "+mat.group() + " # " + mat.group(3));
            else
                System.out.println("didn't match.");
        }
    }
}

  紅字部份表示match,其中group(3)的日,限定到1~31,個位數可以前補0。美中不足的是,2/31這個日期也能pass,而Java的DateFormat也提供檢驗的method,使用方式如下:

public static boolean isValidDateStr(String date) {
    try {
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); // YYYY/MM/DD 短日期格式
        df.setLenient(false);   // Lenient:寛鬆,設為false亦即2/31也不能pass
        df.parse(date);
    } catch (ParseException e) {
        return false;
    } catch (IllegalArgumentException e) {
        return false;
    }
    return true;
}

arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()