如何在Android TextInputLayout中实现图示密码错误提示及第三类错误正则
Android TextInputLayout 密码错误提示实现方案

实现步骤
- 布局配置
首先在布局中嵌套使用TextInputLayout与TextInputEditText,开启错误提示和密码可见切换功能:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/til_password" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEnabled="true" app:passwordToggleEnabled="true"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入密码" android:inputType="textPassword"/> </com.google.android.material.textfield.TextInputLayout>
- 逻辑校验配置
给密码输入框添加文本变化监听,实时校验输入内容,匹配到对应规则时调用TextInputLayout的setError()方法展示提示即可,示例代码(Kotlin):
et_password.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val password = s.toString() val specialCharRegex = Regex("^(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?]).+$") when { password.length < 8 -> til_password.error = "密码长度不能少于8位" !password.matches(Regex("^(?=.*[A-Za-z])(?=.*\\d).+$")) -> til_password.error = "密码必须同时包含字母和数字" !password.matches(specialCharRegex) -> til_password.error = "密码必须包含至少1个特殊字符" else -> til_password.error = null } } override fun afterTextChanged(s: Editable?) {} })
第三类错误正则表达式
参考效果中的第三类错误一般指密码未包含至少1个特殊符号,对应正则如下:
- 仅校验是否包含特殊符号(可直接插入上述校验逻辑使用):
^(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?]).+$ - 全量密码规则校验(同时满足8位以上、包含大小写字母、数字、特殊符号,可用于最终提交校验):
^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?]).{8,}$
注:如果业务允许的特殊符号范围有调整,仅需要修改正则中
[]内的符号列表即可。
内容的提问来源于stack exchange,提问作者Prosenjith Roy
相关产品推荐
相关产品推荐

