大小写字母数字和特殊符号验证
由于功能需要,我的项目注册和设置密码时候 需要设置密码规则为 大小写字母数字和特殊符号,然后查了一番,结果如下:
第一步是布局:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_margin="15dp"
android:layout_weight="3"
android:hint="请输入包含大小写字母数字和特殊符号的密码"
android:layout_height="wrap_content"
android:id="@+id/et_password"></EditText>
<Button
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="登录验证"
android:textColor="@color/white"
android:id="@+id/btn_login"
></Button>
</LinearLayout>在这里插入代码片
第二步是使用的代码方法:
private void initPassword() {
EditText et_password=findViewById(R.id.et_password);
Button btn_login=findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(TextUtils.isEmpty(et_password.getText())){
Toast.makeText(MainActivity.this,"不能为空",Toast.LENGTH_SHORT).show();
return;
}
if(!verifyPassword(et_password.getText().toString())){
Toast.makeText(MainActivity.this,"请输入符合规则的密码",Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(MainActivity.this,"恭喜您 验证通过",Toast.LENGTH_SHORT).show();
}
});
}
public boolean verifyPassword(String password){
String x = "^(?![A-Z]*$)(?![a-z]*$)(?![0-9]*$)(?![^a-zA-Z0-9]*$)\\S+$";//4选2
x = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,16}$";//4选三
if (Pattern.matches(x,password)){
return true;
}
return false;
}
ok 已经测试过了,大家可以试试,如果有更好的方法麻烦留言告知。