首页

关于apache的commons-validator源码包中的DateValidator日期校验器对日期格式进行校验验证

标签:DateValidator,日期验证器,validator,commons-validator,apache     发布时间:2018-02-22   

一、前言

基于apachecommons-validator源码包中的org.apache.commons.validator.DateValidator类,对日期类型Date格式进行有效验证isValid等。

二、源码说明

package org.apache.commons.validator;@b@@b@import java.text.DateFormat;@b@import java.text.ParseException;@b@import java.text.SimpleDateFormat;@b@import java.util.Locale;@b@@b@public class DateValidator@b@{@b@  private static final DateValidator DATE_VALIDATOR = new DateValidator();@b@@b@  public static DateValidator getInstance()@b@  {@b@    return DATE_VALIDATOR;@b@  }@b@@b@  public boolean isValid(String value, String datePattern, boolean strict)@b@  {@b@    if ((value == null) || (datePattern == null) || (datePattern.length() <= 0))@b@    {@b@      return false;@b@    }@b@@b@    SimpleDateFormat formatter = new SimpleDateFormat(datePattern);@b@    formatter.setLenient(false);@b@    try@b@    {@b@      formatter.parse(value);@b@    } catch (ParseException e) {@b@      return false;@b@    }@b@@b@    return ((!(strict)) || (datePattern.length() == value.length()));@b@  }@b@@b@  public boolean isValid(String value, Locale locale)@b@  {@b@    if (value == null) {@b@      return false;@b@    }@b@@b@    DateFormat formatter = null;@b@    if (locale != null)@b@      formatter = DateFormat.getDateInstance(3, locale);@b@    else {@b@      formatter = DateFormat.getDateInstance(3, Locale.getDefault());@b@    }@b@@b@    formatter.setLenient(false);@b@    try@b@    {@b@      formatter.parse(value);@b@    } catch (ParseException e) {@b@      return false;@b@    }@b@@b@    return true;@b@  }@b@}