前言
在android中, 请求网络前,一般都需要校验参数值是否正确,并 Toast 提示错误信息。
上使用代码:
//校验请求网络前的参数 boolean isValid = new VerifyChar() .with("校验的参数1") .required("参数1必须填写") .betweenLength(3,6,"参数1必须是3到6位") .equal("要等于参数1的值","你们并不相等") //使用replace替换空格后,再做其它校验 .with("校验的 参数2",true) .minLength(5,"参数2必须大于5位") .maxLength(8,"参数2必须小于8位") //正则验证 .matches("^[a-zA-Z0-9]{6,16}$","请输入正确的格式") //.isValid();//不弹出错误提示 .isValid(this);//弹出错误提示 if(isValid){ //请求网络 }
接下来我们看一下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; } }
if(!isValid){ return this;} 校验之前先判断,是否已经校验不通过了。 如果已经不通过了,就直接返回this,不再去校验。