如何在 flutter 中添加年份的范围验证

How to add range validation for year in flutter

我尝试添加年份范围验证,它必须在 1850 年到当前年份之间。我已经试过了,但它不起作用。

这是我试过的代码

  String validateestablishedyear(String value) {
    var date = new DateTime.now();
    int currentYear = date.year;
    int userinputValue = 0;
    print('currentYear = $currentYear');
    print('input value = $value');
    print('value = ${value is int}');
    print('value = ${value is String}');

    if (value is String && value.length == 0) {
      return "Established Year is Required";
    } else {
      userinputValue = int.parse(value);
    }

    if (userinputValue < 1850 && userinputValue >= currentYear) {
      return "Year must be between 1850 and $currentYear";
    }
    return null;
  }

只需更改您的代码如下,

if (userinputValue < 1850 || userinputValue >= currentYear) {
  return "Year must be between 1850 and $currentYear";
}

你的逻辑不对。你应该使用 || 而不是 &&