1. 程式人生 > >Android註解方式實現表單校驗

Android註解方式實現表單校驗

view print tde try success lte ise rdb emp

在開發中總會遇到輸入框的輸入規則限制

比如 電話輸入框電話號碼的校驗,密碼規則的校驗等 ,我們通常做法是提交操作時對每個輸入框的輸入內容進行校驗,很多的if else ,代碼看起來很亂,其實我們可以用反射註解的方式去聲明一些判斷規則這樣會更好,代碼可讀性更強。

java反射文章推薦:http://www.jianshu.com/p/5b3acad0f025

下面我們通過一個例子去講解註解方式去實現表達式的校驗

技術分享圖片

這個包下定義的是註解實體類,每一個類都是一個註解規則,如Index類代碼:

技術分享圖片

技術分享圖片

這個包下都是一些javabean, 如AttrBean代碼:

技術分享圖片

BaseBean基礎類,每個bean是一個規則javabean類,

技術分享圖片

結果回調類

技術分享圖片

技術分享圖片

處理回調校驗結果

技術分享圖片

上面主要是校驗器和工具類:

public class ValidateUtil {

/**
* 設置校驗view的信息
* @param view
* @param isEditText
* @param msg
* @param validateResult
*/
private static void setViewInfo(Object view, boolean isEditText, String msg, IValidateResult validateResult) {
if (isEditText) {
validateResult.onValidateError(msg, ((EditText) view));
} else {
validateResult.onValidateError(msg, null);
}
}

/**
* 不可為空
* @param view
* @param isEt
* @param msg
* @param validateResult
* @return
*/
public static boolean notNull(Object view, boolean isEt, String msg, IValidateResult validateResult) {
if (TextUtils.isEmpty(((TextView) view).getText().toString())) {
setViewInfo(view, isEt, msg, validateResult);
return true;
}
return false;
}

/**
* 判斷是否為空
* @param view
* @return
*/
public static boolean isNull(Object view) {
if (view == null)
throw new NullPointerException("view can not be null");
if (TextUtils.isEmpty(((TextView) view).getText().toString())) {
return true;
}
return false;
}

/**
* 根據正則表達式校驗
* @param view
* @param isEt
* @param bean
* @param validateResult
* @return
*/
public static boolean checkPattern(Object view, boolean isEt, PatternBean bean, IValidateResult validateResult) {
if (isNull(view)) return true;

Pattern r = Pattern.compile(bean.pattern);
Matcher m = r.matcher(((TextView) view).getText().toString());
if (!m.matches()) {
setViewInfo(view, isEt, bean.msg, validateResult);
return true;
}
return false;
}

/**
* 最大長度校驗
* @param view
* @param isEt
* @param bean
* @param validateResult
* @return
*/
public static boolean maxLenght(Object view, boolean isEt, LengthBean bean, IValidateResult validateResult) {
if (isNull(view)) return true;

if (((TextView) view).getText().toString().length() > bean.length) {
setViewInfo(view, isEt, bean.msg, validateResult);
return true;
}
return false;
}
}

public class ValidateManager {
private static final String TAG = "ValidateManager";
/**
* 註冊的頁面
*/
private static Map<Object, List<AttrBean>> registList = new HashMap<>();
/**
* 類型
*/
private static final String TYPE_NOTNULL = "NotNull";
private static final String TYPE_PATTERN = "PATTERN";
private static final String TYPE_MAXLENGTH = "MAXLENGTH";
private static final String TYPE_MINLENGTH = "MINLENGTH";
private static final String TYPE_PASSWORDFIRST = "PASSWORD_FIRST";
private static final String TYPE_PASSWORDSECOND = "PASSWORD_SECOND";
private static final String TYPE_SKIP = "SKIP";

public static void check(Object activity, boolean isSkip, IValidateResult validateResult) {
if (activity == null || validateResult == null) return;
List<AttrBean> list = registList.get(activity);
if (list == null) return;
for (AttrBean attrBean : list) {
if (attrBean.index == null) {
return;
}
}
Collections.sort(list, new Comparator<AttrBean>() {
public int compare(AttrBean arg0, AttrBean arg1) {
return arg0.index.compareTo(arg1.index);
}
});
for (AttrBean attrBean : list) {
for (Basebean bean : attrBean.annos) {
if (isSkip) {
if (TYPE_SKIP.equals(attrBean.annos.getLast().type)) {
break;
}
}
if (TYPE_NOTNULL.equals(bean.type)) {
if (ValidateUtil.notNull(attrBean.view, attrBean.isEditText, bean.msg, validateResult)) {
return;
}
} else if (TYPE_PATTERN.equals(bean.type)) {
if (ValidateUtil.checkPattern(attrBean.view, attrBean.isEditText, (PatternBean) bean, validateResult)) {
return;
}
} else if (TYPE_MAXLENGTH.equals(bean.type)) {
if (ValidateUtil.maxLenght(attrBean.view, attrBean.isEditText, (LengthBean) bean, validateResult)) {
return;
}
} else if (TYPE_MINLENGTH.equals(bean.type)) {
if (ValidateUtil.minLenght(attrBean.view, attrBean.isEditText, (LengthBean) bean, validateResult)) {
return;
}
} else if (TYPE_PASSWORDFIRST.equals(bean.type)) {
if (ValidateUtil.isNull(attrBean.view)) {
return;
}
pwd1Attr = attrBean;
} else if (TYPE_PASSWORDSECOND.equals(bean.type)) {
if (ValidateUtil.password(attrBean, pwd1Attr, (PasswordBean) bean, validateResult)) {
return;
}
pwd1Attr = null;
}
}
}
validateResult.onValidateSuccess();
pwd1Attr = null;
}

private static AttrBean pwd1Attr = null;

private static class ValidateRegRunnable implements Runnable {
Object target;

public ValidateRegRunnable(Object target) {
this.target = target;
}

@Override
public void run() {
try {
Class clazz = target.getClass();

for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(NotNull.class) ||
field.isAnnotationPresent(Pattern.class) ||
field.isAnnotationPresent(MaxLength.class) ||
field.isAnnotationPresent(MinLength.class) ||
field.isAnnotationPresent(Index.class) ||
field.isAnnotationPresent(PasswordFirst.class) ||
field.isAnnotationPresent(PasswordSecond.class)) {

if (field.getType() != EditText.class) {
throw new RuntimeException("annotation must be on the EditText");
}
field.setAccessible(true);
List<AttrBean> editTextMap = registList.get(target);
if (editTextMap == null) {
editTextMap = new LinkedList<>();
registList.put(target, editTextMap);
}
AttrBean attr = new AttrBean();
attr.name = field.getName();
attr.view = field.get(target);

if (field.getType() == EditText.class) {
attr.isEditText = true;
} else if (field.getType() == TextView.class) {
attr.isEditText = false;
}
if (attr.annos == null) {
attr.annos = new LinkedList<>();
}
editTextMap.add(attr);

if (field.isAnnotationPresent(NotNull.class))
attr.annos.add(validateType(field, TYPE_NOTNULL));
if (field.isAnnotationPresent(Pattern.class))
attr.annos.add(validateType(field, TYPE_PATTERN));
if (field.isAnnotationPresent(MaxLength.class)) {
attr.annos.add(validateType(field, TYPE_MAXLENGTH));
if (attr.view != null && attr.isEditText) {
int length = field.getAnnotation(MaxLength.class).length();
((EditText) attr.view).setFilters(new InputFilter[]{new InputFilter.LengthFilter(length)});
}
}
if (field.isAnnotationPresent(MinLength.class))
attr.annos.add(validateType(field, TYPE_MINLENGTH));
if (field.isAnnotationPresent(PasswordFirst.class)) {
attr.annos.add(validateType(field, TYPE_PASSWORDFIRST));
if (attr.view != null && attr.isEditText) {
((EditText) attr.view).setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
if (field.isAnnotationPresent(PasswordSecond.class)) {
attr.annos.add(validateType(field, TYPE_PASSWORDSECOND));
if (attr.view != null && attr.isEditText) {
((EditText) attr.view).setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
if (field.isAnnotationPresent(Index.class))
attr.index = field.getAnnotation(Index.class).value();
if (field.isAnnotationPresent(Skip.class))
attr.annos.add(validateType(field, TYPE_SKIP));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

/**
* 根據不同類型校驗
* @param field
* @param type
* @return
* @throws IllegalAccessException
*/
private static Basebean validateType(Field field, String type) throws IllegalAccessException {
if (type.equals(TYPE_NOTNULL)) {
NotNull notnull = field.getAnnotation(NotNull.class);
NotNullBean bean = new NotNullBean();
bean.msg = notnull.msg();
bean.type = type;
return bean;
} else if (type.equals(TYPE_PATTERN)) {
Pattern re = field.getAnnotation(Pattern.class);
PatternBean reBean = new PatternBean();
reBean.msg = re.msg();
reBean.type = TYPE_PATTERN;
reBean.pattern = re.pattern();
return reBean;
} else if (type.equals(TYPE_MAXLENGTH)) {
MaxLength anno = field.getAnnotation(MaxLength.class);
LengthBean bean = new LengthBean();
bean.msg = anno.msg();
bean.type = TYPE_MAXLENGTH;
bean.length = anno.length();
return bean;
} else if (type.equals(TYPE_MINLENGTH)) {
MinLength anno = field.getAnnotation(MinLength.class);
LengthBean bean = new LengthBean();
bean.msg = anno.msg();
bean.type = TYPE_MINLENGTH;
bean.length = anno.length();
return bean;
} else if (type.equals(TYPE_PASSWORDFIRST)) {
PasswordBean bean = new PasswordBean();
bean.type = TYPE_PASSWORDFIRST;
return bean;
} else if (type.equals(TYPE_PASSWORDSECOND)) {
PasswordSecond anno = field.getAnnotation(PasswordSecond.class);
PasswordBean bean = new PasswordBean();
bean.msg = anno.msg();
bean.type = TYPE_PASSWORDSECOND;
return bean;
} else if (type.equals(TYPE_SKIP)) {
Basebean bean = new Basebean();
bean.type = TYPE_SKIP;
return bean;
}

return null;
}

/**
* 註冊
* @param target
*/
public static void regist(final Object target) {
new Thread(new ValidateRegRunnable(target)).start();
}

/**
* 解註冊
* @param target
*/
public static void unregist(Object target) {
registList.remove(target);
}
}

我只貼出了部分代碼,可以根據項目實際需求去添加規則,再把相應的校驗器代碼擴展到這個類裏。

我們在主頁面使用 按照正常的註解方式去實現 如下:

技術分享圖片

index是校驗的順序,需要正則表達式校驗的輸入框我們通過pattern去通過正則表達式去實現,minLength和maxLength是最小最大長度校驗

完成後調用ValidateManager.check(this , isSkip , this);實現校驗功能,經過回調處理(isSkip是否可以忽略不校驗此項)

技術分享圖片

可以對指定輸入框的view進行錯誤提醒,比如上面 對輸入框背景色設置紅色等操作。需源碼的留郵箱。

Android註解方式實現表單校驗