Android annotation method for form validation

Source: Internet
Author: User

The input rules limit of input box is always encountered in development.

For example, the telephone input box phone number verification, password rules, such as check, we usually do is to submit the operation of each input box to verify the input, a lot of if else, the code looks very messy, in fact, we can use reflection annotations to declare some of the rules of judgment this will be better, code readability is stronger.

Java Reflection Article Recommendation: http://www.jianshu.com/p/5b3acad0f025

Let's use an example to explain how to verify the expression

This package defines the annotation entity class, each of which is an annotation rule, such as the Index class code:

Under this package are some javabean, such as the Attrbean code:

Basebean base class, each bean is a rule javabean class,

Result Callback Class

Processing callback Checksum results

The above are mainly validators and tool classes:

public class Validateutil {

/**
* Set the check view information
* @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);
}
}

/**
* Cannot be empty
* @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;
}

/**
* Determine if it is empty
* @param view
* @return
*/
public static Boolean isNull (Object view) {
if (view = = null)
throw new NullPointerException ("View can not is null");
if (Textutils.isempty ((TextView) view). GetText (). toString ())) {
return true;
}
return false;
}

/**
* According to the regular expression check
* @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;
}

/**
* Maximum length Check
* @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";
/**
* Registered Page
*/
private static Map<object, list<attrbean>> registlist = new hashmap<> ();
/**
* Type
*/
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 is 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 ();
}
}
}

/**
* According to the different types of calibration
* @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;
}

/**
* Registration
* @param target
*/
public static void Regist (final Object target) {
New Thread (new validateregrunnable). Start ();
}

/**
* Unlock Registration
* @param target
*/
public static void Unregist (Object target) {
Registlist.remove (target);
}
}

I've just posted some code that can add rules based on the actual requirements of the project, and then extend the corresponding validator code into this class.

We do this in the main page using the following normal annotations:

Index is the order of validation, the input box that requires regular expression validation we use the pattern to achieve through regular expressions, minlength and maxlength is the minimum maximum length check

After completion call Validatemanager.check (this, Isskip, this), implement the checksum function, after the callback processing (Isskip can ignore do not check this item)

You can make an error alert to the view of the specified input box, such as setting red on the background color of the input box. Need to stay in the source mail.

Android annotation method for form validation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.