【问题标题】:Flutter TextField input validation for a dateFlutter TextField 输入验证日期
【发布时间】:2020-10-09 13:33:22
【问题描述】:

我正在尝试编写一个日期输入控件,它接受像 23/12/1997 这样的日期。我想做的是自动为用户插入 / 字符。因此,当他们输入 23 时,侦听器返回 23/,以便他们可以输入 12。此时,侦听器再次添加 /,让用户通过输入 1997 来完成日期。 我的 TextEditingController 代码一半工作,看起来像这样:

final _controller = TextEditingController();
_controller.addListener(() {
      String text = _controller.text;
      if (text.length == 2) {
        text += '/';
      }
      if (text.length == 5) {
        text += '/';
      }
      _controller.value = _controller.value.copyWith(
        text: text,
        selection:
            TextSelection(baseOffset: text.length, extentOffset: text.length),
        composing: TextRange.empty,
      );
      print(_controller.text);
    }

所以它可以正常工作,直到用户犯错并需要回溯。一旦 / 被删除,它就会立即被替换,从而停止对日期的任何进一步编辑。

为了让它工作,我需要访问之前输入的文本以确定用户是否正在退格。所以如果text == 23/ && previous_text == 23/1 那么我可以从文本中删除/。

我发现了这个问题textfield must only accept numbers,我认为它可能对我有所帮助,但我不确定如何实现现有小部件并覆盖其方法。当然在 TextEditingController 中可能有更简单的方法来做到这一点?

【问题讨论】:

  • 您可以检查包裹以掩盖日期,例如pub.dev/packages/date_text_masked
  • 感谢@zero-live。我看过几个包,他们做我想做的事。但从自己学习的角度来看,我想继续挑战自己做。

标签: date validation flutter dart textfield


【解决方案1】:

我找到了解决日期验证输入所需的内容。它并不完美,但对于我正在尝试做的事情来说已经足够了。我只需要查看 TextField() 的 inputFormatters 方法。这允许对输入文本进行操作以将其转换为任意数量的用户定义格式。我为任何想尝试的人提供了一段代码:

  class _DateFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue prevText, TextEditingValue currText) {
    int selectionIndex;

    // Get the previous and current input strings
    String pText = prevText.text;
    String cText = currText.text;
    // Abbreviate lengths
    int cLen = cText.length;
    int pLen = pText.length;

    if (cLen == 1) {
      // Can only be 0, 1, 2 or 3
      if (int.parse(cText) > 3) {
        // Remove char
        cText = '';
      }
    } else if (cLen == 2 && pLen == 1) {
      // Days cannot be greater than 31
      int dd = int.parse(cText.substring(0, 2));
      if (dd == 0 || dd > 31) {
        // Remove char
        cText = cText.substring(0, 1);
      } else {
        // Add a / char
        cText += '/';
      }
    } else if (cLen == 4) {
      // Can only be 0 or 1
      if (int.parse(cText.substring(3, 4)) > 1) {
        // Remove char
        cText = cText.substring(0, 3);
      }
    } else if (cLen == 5 && pLen == 4) {
      // Month cannot be greater than 12
      int mm = int.parse(cText.substring(3, 5));
      if (mm == 0 || mm > 12) {
        // Remove char
        cText = cText.substring(0, 4);
      } else {
        // Add a / char
        cText += '/';
      }
    } else if ((cLen == 3 && pLen == 4) || (cLen == 6 && pLen == 7)) {
      // Remove / char
      cText = cText.substring(0, cText.length - 1);
    } else if (cLen == 3 && pLen == 2) {
      if (int.parse(cText.substring(2, 3)) > 1) {
        // Replace char
        cText = cText.substring(0, 2) + '/';
      } else {
        // Insert / char
        cText =
            cText.substring(0, pLen) + '/' + cText.substring(pLen, pLen + 1);
      }
    } else if (cLen == 6 && pLen == 5) {
      // Can only be 1 or 2 - if so insert a / char
      int y1 = int.parse(cText.substring(5, 6));
      if (y1 < 1 || y1 > 2) {
        // Replace char
        cText = cText.substring(0, 5) + '/';
      } else {
        // Insert / char
        cText = cText.substring(0, 5) + '/' + cText.substring(5, 6);
      }
    } else if (cLen == 7) {
      // Can only be 1 or 2
      int y1 = int.parse(cText.substring(6, 7));
      if (y1 < 1 || y1 > 2) {
        // Remove char
        cText = cText.substring(0, 6);
      }
    } else if (cLen == 8) {
      // Can only be 19 or 20
      int y2 = int.parse(cText.substring(6, 8));
      if (y2 < 19 || y2 > 20) {
        // Remove char
        cText = cText.substring(0, 7);
      }
    }

    selectionIndex = cText.length;
    return TextEditingValue(
      text: cText,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}

要使用它,只需从 Textfield() 调用它,如下所示。我还合并了两个内置方法。 WhitelistingTextInputFormatter() 只允许输入数字和斜杠 (/) 字符,LengthLimitingTextInputFormatter() 限制允许的字符数。后者可以使用 TextField() 的 maxLength 参数来实现,但此处仅作为示例。请注意,还有一个 BlacklistingTextInputFormatter() 可以按照您的预期进行。

WhitelistingTextInputFormatter 被移除使用 FilteringTextInputFormatter.allow(RegExp("[0-9-]")), 来替换,如果你想改变分割符号 (当前是 "/"),请将其添加到 RegExp(....)。

TextField(
  // maxLength: 10,
  keyboardType: TextInputType.datetime,
  controller: _controllerDOB,
  focusNode: _focusNodeDOB,
  decoration: InputDecoration(
    hintText: 'DD/MM/YYYY',
    counterText: '',
  ),
  inputFormatters: [
    WhitelistingTextInputFormatter(RegExp("[0-9/]")),
    LengthLimitingTextInputFormatter(10),
    _DateFormatter(),
  ],
),

【讨论】:

  • 所以如果你想格式化和验证'DD/MM/YYYY - DD/MM/YYYY',基本上两个日期在一个字符串中?你是怎么做的。
  • WhitelistingTextInputFormatter 现已弃用,请使用 FilteringTextInputFormatter.allow(RegExp("[0-9/]"))
【解决方案2】:

你可以使用flutter制作的日期选择器对话框。

DateTime _date = DateTime.now()


onPressed: () {
  showDatePicker(
    context: context,
    initialDate: _date,
    firstDate: DateTime(2020),
    lastDate: DateTime(2021),
    ).then((date) {
      setState(() {
    _date = date;
    });
  });
},

【讨论】:

  • 谢谢@Nehal。我知道这个 Flutter 功能,并且已经准备好当前允许日期输入。但我对此很固执,想用我自己的文本输入小部件自己解决它。
【解决方案3】:

我发现您的代码是一个很棒的实用程序,没有任何依赖关系。我冒昧地做了一些修改并想把它发回这里,因为我发现你的概念在 UI 上非常简洁和轻量级。要求是;

  1. 验证非 31 天月份和闰年的日期。模组非常简单。

  2. 防止用户在不希望的地方输入“/”,这会使算法偏离轨道。最简单的解决方案是使

keyboardType:TextInputType.number,在TextField中

这非常适用于移动设备。 但是 Flutter 是跨平台的,对于带有物理键盘的设备,这种解决方案可能并非万无一失。我尝试了各种检查和阻止,但只成功了一部分;即,用户仍然可以在日和月的数字之间输入“/”。我认为 KB 输入和编程格式化程序之间存在内部延迟。

以下是 _DateFormatter 的修改代码。我使用 /// 概念来区分我的 cmets。它们应该与原始的 // cmets 一起阅读。

class _DateFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
  TextEditingValue prevText, TextEditingValue currText) {
int selectionIndex;

String date;
String month;
int year;

// Get the previous and current input strings
String pText = prevText.text;
String cText = currText.text;

cText = cText.replaceAll("//", "/");

// Abbreviate lengths
int cLen = cText.length;
int pLen = pText.length;

/// ENTERING THE DATE
if (cLen == 1) {
  ///  User enters the first digit of the  date. The first digit
  // Can only be 0, 1, 2 or 3
  if (int.parse(cText) > 3) {
    // Remove char
    cText = '';
  }
} else if (cLen == 2 && pLen == 1) {
  /// User has already entered a valid first digit of the date, now he
  /// enters the second digit of the date; but
  // Days cannot be greater than 31
  int dd = int.parse(cText.substring(0, 2));
  if (dd == 0 || dd > 31) {
    // Remove char
    cText = cText.substring(0, 1);
  } else {
    /// User has entered a valid date (between 1 and 31). So now,
    // Add a / char
    cText += '/';
  }
  /// ENTERING THE MONTH
} else if (cLen == 4) {
  /// after entering a valid date and programmatic insertion of '/', now User has entered
  /// the first digit of the Month. But, it
  // Can only be 0 or 1
  /// (and, not  '/' either)
  if (int.parse(cText.substring(3, 4)) > 1 || cText.substring(3, 4) == "/") {
    // Remove char
    cText = cText.substring(0, 3);
  }
} else if (cLen == 5 && pLen == 4) {
  int mm = int.parse(cText.substring(3, 5));
  int dd = int.parse(cText.substring(0, 2));
  /// User has entered the second digit of the Month, but the
  // Month cannot be greater than 12
  /// Also, that entry cannot be '/'
  if ((mm == 0 || mm > 12|| cText.substring(3, 5) == "/") ||
      /// If the date is 31, the month cannot be Apr, Jun, Sept or Nov
    (dd == 31 && (mm == 02 || mm == 04 || mm == 06 || mm == 09 || mm == 11)) ||
      /// If the date is greater than 29, the month cannot be Feb
      /// (Leap years will be dealt with, when user enters the Year)
      (dd > 29 && (mm == 02))) {
      // Remove char
      cText = cText.substring(0, 4);
  }
  else if (cText.length == 5) {
    /// the Month entered is valid; so,
    // Add a / char
    cText += '/';
  }
} else if ((cLen == 3 && pLen == 4) || (cLen == 6 && pLen == 7)) {
  // Remove / char
  cText = cText.substring(0, cText.length - 1);
} else if (cLen == 3 && pLen == 2) {
  if (int.parse(cText.substring(2, 3)) > 1) {
    // Replace char
    cText = cText.substring(0, 2) + '/';
  } else {
    // Insert / char
    cText =
        cText.substring(0, pLen) + '/' + cText.substring(pLen, pLen + 1);
  }
/// ENTERING THE YEAR
} else if (cLen == 6 && pLen == 5) {
  // Can only be 1 or 2 - if so insert a / char
  int y1 = int.parse(cText.substring(5, 6));
  if (y1 < 1 || y1 > 2) {
    // Replace char
    /// i.e, add '/' after the 5th position
    cText = cText.substring(0, 5) + '/';
  } else {
    // Insert / char
    cText = cText.substring(0, 5) + '/' + cText.substring(5, 6);
  }
} else if (cLen == 7) {
  /// the first digit of year
  // Can only be 1 or 2
  int y1 = int.parse(cText.substring(6, 7));
  if (y1 < 1 || y1 > 2) {
    // Remove char
    cText = cText.substring(0, 6);
  }
} else if (cLen == 8) {
  // Can only be 19 or 20
  /// Also, there cannot be / typed by the user
  String y2 = cText.substring(6, 8);
  if (y2 != "19" && y2 != "20") {
    // Remove char
    cText = cText.substring(0, 7);
  }
} else if (cLen == 9) {
  /// There cannot be / typed by the user
  if (cText.substring(8, 9) == "/") {
    // Remove char
    cText = cText.substring(0, 8);
  }
} else if (cLen == 10) {
  /// There cannot be / typed by the user
  if (cText.substring(9, 10) == "/") {
    // Remove char
    cText = cText.substring(0, 9);
  }
  /// If the year entered is not a leap year but the date entered is February 29,
  /// it will be advanced to the next valid date
  date = cText.substring(0, 2);
  month = cText.substring(3, 5);
  year = int.parse(cText.substring(6, 10));
  bool isNotLeapYear = !((year % 4 == 0) && (year % 100 != 0) ||
      (year % 400 == 0));
  if (isNotLeapYear && month == "02" && date == "29") {
    cText = "01/03/$year";
  }
}

selectionIndex = cText.length;
return TextEditingValue(
  text: cText,
  selection: TextSelection.collapsed(offset: selectionIndex),
);
}
} // END OF class _DateFormatter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多