前言
之前用java代码, 封装了一次, https://blog.csdn.net/qq_23227311/article/details/80773575
首先我们先看看, 封装后 请求网络时,对参数校验的代码:
if(VerifyChar() .with("1321111111")//要校验的字符 .required("请输入用户名")//必填 (error错误信息,可传R.string.**) .matches("^[a-zA-Z]\\w{5,17}\$","用户名输入错误") .with("a123456") .required("请输入密码") .betweenLength(8,16,"密码请输入8到16位") .isValid(context)){ //请求网络.... }
看看 VerifyChar 类, 封装了哪些方法:
import android.content.Context; import android.text.TextUtils; import android.widget.Toast; import java.util.regex.Pattern; /** * 校验字符 * zhanhai */ public class VerifyChar { /**校验的值*/ private String value; /**是否验证通过*/ private boolean isValid; /**本次校验不通过的错误信息*/ private String error; public VerifyChar(){ isValid = true; error = null; } /** * @param value 要校验的字符 */ public VerifyChar with(String value){ this.value= value; return this; } /** * @param value 要校验的字符 * @param isRemoveSpace 是否去掉空格 */ public VerifyChar with(String value,boolean isRemoveSpace){ if(value!=null&&isRemoveSpace){ this.value= value.replace(" ", ""); } return this; } /** * 必填 * @param error 错误信息 * @return */ public VerifyChar required(String error){ if(!isValid){ return this;} if(TextUtils.isEmpty(this.value)){//是空字符 setFailureInfo(error); } return this; } /** * 最小长度校验 * @param min 最小长度(包含) * @param error 错误信息 * @return */ public VerifyChar minLength(int min, String error){ if(!isValid){ return this;} if(this.value.length()<min){ setFailureInfo(error); } return this; } /** * 最大长度校验 * @param max 最大长度(包含) * @param error 错误信息 * @return */ public VerifyChar maxLength(int max, String error){ if(!isValid){ return this;} if(this.value.length()>max){ setFailureInfo(error); } return this; } /** * 在 ... 之中 * @param min 最小长度(包含) * @param max 最大长度(包含) * @param error 错误信息 * @return */ public VerifyChar betweenLength(int min, int max, String error){ if(!isValid){ return this;} if(this.value.length()>max||this.value.length()<min){ setFailureInfo(error); } return this; } /** * 比较this.value是否等于arg0 * @param arg0 要比较的值 * @param error 错误信息 * @return */ public VerifyChar equal(String arg0, String error){ if(!isValid){ return this;} if(!this.value.equals(arg0)){ setFailureInfo(error); } return this; } /** * 正则校验 * @param regularExpression 正则表达式 * @param error 错误信息 * @return */ public VerifyChar matches(String regularExpression, String error){ if(!isValid){ return this;} if(!Pattern.matches(regularExpression,this.value)){ setFailureInfo(error); } return this; } /** * 设置校验失败信息 * @param error */ void setFailureInfo(String error){ this.error = error; this.isValid = false; } /** * 是否验证通过 * @return */ public boolean isValid(){ return this.isValid; } /** * 是否验证通过,提示错误信息 * @param context * @return */ public boolean isValid(Context context){ if(null!=error&&!this.isValid){ Toast.makeText(context,error,Toast.LENGTH_SHORT).show(); } return this.isValid; } }
欢迎留言,指教我一下, 谢谢各位大佬们