gpt4 book ai didi

java - 如何在 Java Android Studio 中验证日月和年,

转载 作者:行者123 更新时间:2023-12-04 08:02:21 26 4
gpt4 key购买 nike

我有这个代码,但是 runValidations 没有检查月份和年份是否真的正确。编译器没有显示任何错误或任何内容。我一遍又一遍地阅读代码,但不知道如何解决此验证问题,非常感谢您的帮助。
我已经尝试了我能想到的所有可能的事情,但我还没有到任何地方。

 {

ActivityMainBinding binding;
boolean isPasswordHidden = true;

public static final String USER_EXTRA = "USER_EXTRA";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.button.setOnClickListener(this::runValidations);
binding.ivHidden.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
isPasswordHidden = !isPasswordHidden;
if (isPasswordHidden) {
binding.ivHidden.setImageResource(R.drawable.ic_baseline_visibility_off_24);
binding.etPassword.setTransformationMethod(new PasswordTransformationMethod());
} else {
binding.ivHidden.setImageResource(R.drawable.ic_baseline_visibility_24);
binding.etPassword.setTransformationMethod(null);
}
binding.etPassword.setSelection(binding.etPassword.getText().length());
}
});
binding.cbTerms.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
binding.button.setEnabled(isChecked);
}
});
}


public void runValidations(View view) {

boolean isEverythingOk = verifyForEmptyField(binding.etName)
&& verifyForEmptyField(binding.etLastName)
&& verifyForEmptyField(binding.etMail)
&& verifyForEmptyField(binding.etPassword)
&& verifyForEmptyField(binding.etDays)
&& verifyForEmptyField(binding.etMonths)
&& verifyForEmptyField(binding.etYears)
&& validateEmailAddressField()
&& validatePasswordLength()
&& validateDay()
&& validateMonth()
&& validateYear();

if (isEverythingOk) {
Intent intent = new Intent(this, SuccessActivity.class);
User user = new User(
getTrimmedText(binding.etName),
getTrimmedText(binding.etLastName),
getTrimmedText(binding.etMail),
getTrimmedText(binding.etPassword),
"", ""
);
intent.putExtra(USER_EXTRA, user);
startActivity(intent);
finish();
}
}


private boolean verifyForEmptyField(EditText editText) {
String fieldContent = getTrimmedText(editText);
boolean isValid = !fieldContent.isEmpty();
if (!isValid) {
editText.setError(getString(R.string.error_empty_field));
}
return isValid;
}

private String getTrimmedText(EditText editText) {
return editText.getText().toString().trim();
}

private boolean validateEmailAddressField() {
boolean isValid = Patterns.EMAIL_ADDRESS.matcher(getTrimmedText(binding.etMail)).matches();
if (!isValid) {
binding.etMail.setError(getString(R.string.error_invalid_email));
}
return isValid;
}

private boolean validatePasswordLength() {
String password = getTrimmedText(binding.etPassword);
boolean isValid = password.length() >= 10;
if (!isValid) {
binding.etPassword.setError(getString(R.string.error_password_lenght));
}
return isValid;
}

private int parseETtoInt(EditText editText) {
try {
String content =getTrimmedText(editText);
return Integer.parseInt(content);
} catch (NumberFormatException e) {
return -1;
}
}

public boolean validateDay() {
int valueD= parseETtoInt(binding.etDays);
boolean isValid = (valueD <= 31 && valueD > 0);
if (!isValid){
binding.etDays.setError(getString(R.string.error_invalid_day));
}
return isValid;
}

public boolean validateMonth() {
int valueM= parseETtoInt(binding.etMonths);
boolean isValid = (valueM >=1 && valueM <= 12);
if (!isValid){
binding.etMonths.setError(getString(R.string.error_invalid_month));
}
return isValid;
}

public boolean validateYear() {
int valueY= parseETtoInt(binding.etYears);
boolean isValid = (valueY < 2021 && valueY > 1900);
if (!isValid){
binding.etYears.setError(getString(R.string.error_invalid_year));
}
return isValid;
}

}
它运行对姓名、姓氏、邮件、密码的验证。除了日期之外的所有内容,运行 avd 我可以在日期上输入任何值,并且当我引入错误值时不会显示错误。

最佳答案

分别验证年、月和日不仅复杂而且容易出错。我建议您验证可以通过组合来自 binding.etYears 的值来形成的完整日期字符串。 , binding.etMonths , 和 binding.etDays .
演示:

import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;

class Main {
// Simulating year, month and day
static String etYears = "2020";
static String etMonths = "2";
static String etDays = "23";

public static void main(String[] args) {
// Tests

System.out.println(isValidDate());

etDays = "30";
System.out.println(isValidDate());

etMonths = "13";
etDays = "23";
System.out.println(isValidDate());

etYears = "1855";
etMonths = "2";
System.out.println(isValidDate());
}

static boolean isValidDate() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-M-d", Locale.ENGLISH)
.withResolverStyle(ResolverStyle.STRICT);

String strDate = etYears + "-" + etMonths + "-" + etDays;
System.out.println(strDate);

try {
LocalDate date = LocalDate.parse(strDate, dtf);
int year = date.getYear();
return year < 2021 && year > 1900;
} catch (DateTimeException e) {
return false;
}
}
}
输出:
2020-2-23
true
2020-2-30
false
2020-13-23
false
1855-2-23
false
了解有关现代日期时间 API 的更多信息Trail: Date Time .
注: java.util日期时间 API 及其格式 API, SimpleDateFormat过时且容易出错。建议完全停止使用它们并切换到 modern date-time API .
  • 无论出于何种原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport将大部分 java.time 功能向后移植到 Java 6 和 7。
  • 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请查看 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project .
  • 关于java - 如何在 Java Android Studio 中验证日月和年,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66392748/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com