我正在尝试使用JSON创建一个注册应用程序来连接并发布到MySQL数据库。我创建了以下if
/ else
语句,以检查空白输入框,密码匹配和正确的电子邮件字符,然后才能将其输入数据库。即使密码不匹配,输入了无效的电子邮件字符或提交了空白文本框,代码也会继续发布JSON。即使存在无效输入,为什么还要提交JSON?
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String check = checkpass.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
try {
if (!inputEmail.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+") && email.length() > 0)
{
Toast.makeText(getApplicationContext(), "Enter Valid Email Address", Toast.LENGTH_LONG).show();
return;
}
else if(name.equals("") || email.equals("")|| password.equals("")||check.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
else if(!password.equals(checkpass))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("User already Registered");
}
}
}
catch (JSONException e) {
}
}
});
答案 0 :(得分:0)
这样做
if(name != null && name.trim().length() ==0 || email != null && email.trim().length() ==0|| password != null && password.trim().length() ==0||check != null && check.trim().length() ==0)
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
答案 1 :(得分:0)
For Empty String
& Email
验证这可能有助于您
Boolean bstremail = (TextUtils.isEmpty(stremail));
Boolean bemail = isEmailValid(stremail);
public isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
现在,您可以轻松Boolean
轻松管理您的验证。