不懂安卓。项目是需要先将后端启动,再将安卓端代码启动后才能运行。
现在想在用户注册时加个验证功能,11位手机号和邮箱格式的验证。应该修改后端还是安卓端代码呢?
某位开发者调用API接口推送消息,请求返回:{"code": "80000000","msg": "Success","requestId": "16233092****287602020201"}。返回"code": "80000000"表示该请求是成功的,但是手机端未收到通知栏消息。
根据题目描述,需要在安卓应用的注册页面添加手机号和邮箱格式的验证功能。对于这个问题,需要修改安卓端代码来实现。
首先,在布局文件中添加手机号和邮箱输入框,并添加相应的验证错误提示信息:
<EditText
android:id="@+id/phoneEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入手机号" />
<TextView
android:id="@+id/phoneErrorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/red"
android:visibility="gone"
android:text="手机号格式不正确" />
<EditText
android:id="@+id/emailEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入邮箱" />
<TextView
android:id="@+id/emailErrorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/red"
android:visibility="gone"
android:text="邮箱格式不正确" />
接着,在对应的Activity中,使用正则表达式对手机号和邮箱进行格式验证,并设置相应的错误提示信息的可见性:
EditText phoneEditText = findViewById(R.id.phoneEditText);
final TextView phoneErrorText = findViewById(R.id.phoneErrorText);
EditText emailEditText = findViewById(R.id.emailEditText);
final TextView emailErrorText = findViewById(R.id.emailErrorText);
//验证手机号格式
phoneEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {
String input = s.toString().trim();
String regex = "^1\\d{10}$";
if (Pattern.matches(regex, input)) {
phoneErrorText.setVisibility(View.GONE);
} else {
phoneErrorText.setVisibility(View.VISIBLE);
}
}
});
//验证邮箱格式
emailEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {
String input = s.toString().trim();
String regex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
if (Pattern.matches(regex, input)) {
emailErrorText.setVisibility(View.GONE);
} else {
emailErrorText.setVisibility(View.VISIBLE);
}
}
});
其中,"^1\d{10}$"表示手机号的正则表达式,"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"表示邮箱的正则表达式。在onTextChanged()方法中获取输入的内容,使用Pattern.matches()方法进行格式验证,然后根据验证结果设置相应的错误提示信息的可见性。
需要注意的是,在使用正则表达式进行验证时,需要对可能出现的特殊字符进行转义,例如正则表达式中的"\"就需要使用"\\"表示。
都可以啊,前端正则一下跟后台正则一下都行,不过前端正则去过滤的话如果涉及到有些手机号是存在的但是正则不通过需要更新APP才可以,如果交于后端来判断的话后端直接修改一下不用重新更新APP会方便些