android-saripaar 是一个基于规则的Android UI输入验证库,通过Annotation来标注验证规则。号称是最简单的Android UI验证规则库。
Saripaar特性:
1. 使用android-saripaar提供的Annotation来标注验证规则
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Required
(
order
=
1
)
@Email
(
order
=
2
)
private
EditText
emailEditText
;
@Password
(
order
=
3
)
@TextRule
(
order
=
4
,
minLength
=
6
,
message
=
"Enter at least 6 characters."
)
private
EditText
passwordEditText
;
@ConfirmPassword
(
order
=
5
)
private
EditText
confirmPasswordEditText
;
@Checked
(
order
=
6
,
message
=
"You must agree to the terms."
)
private
CheckBox
iAgreeCheckBox
;
|
每个规则都是顾名思义的,其中 order 属性
是必须的,用来告诉Saripaar这些输入规则的验证顺序。
2. 初始化一个Validator
1
2
3
4
5
6
7
8
9
|
public
void
onCreate
(
)
{
super
.
onCreate
(
)
;
// Code…
validator
=
new
Validator
(
this
)
;
validator
.
setValidationListener
(
this
)
;
// More code…
}
|
需要一个Validator
和 ValidationListener
。后者用来接收验证结果通知。
3. 实现一个ValidationListener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
class
RegistrationActivity
implements
ValidationListener
{
public
void
onValidationSucceeded
(
)
{
Toast
.
makeText
(
this
,
"Yay! we got it right!"
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
}
public
void
onValidationFailed
(
View
failedView
,
Rule
&
lt
;
?
&
gt
;
failedRule
)
{
String
message
=
failedRule
.
getFailureMessage
(
)
;
if
(
failedView
instanceof
EditText
)
{
failedView
.
requestFocus
(
)
;
(
(
EditText
)
failedView
)
.
setError
(
message
)
;
}
else
{
Toast
.
makeText
(
this
,
message
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
}
}
}
|
onValidationSucceeded()
– 当所有验证规则都通过时调用该函数onValidationFailed(View, Rule>)
– 当验证失败时调用该函数,View为失败的控件,Rule为具体的规则.4. 发起验证
1
2
3
4
5
6
|
registerButton
.
setOnClickListener
(
new
OnClickListener
(
)
{
public
void
onClick
(
View
v
)
{
validator
.
validate
(
)
;
}
}
)
;
|
Validator.validate() 发起验证,并通过 ValidationListener 来通知验证结果。调用函数 Validator.validateAsync()
可以在一个AsyncTask中发起验证。
只需4步即可完成一个界面的输入验证。