首页 > 解决方案 > KeyboardDatePicker MaterialUI - 自定义遮罩格式

问题描述

当使用 Material UI 的 KeyboardDatePicker 时,当格式为 dd/MMM/yyyy(例如 1983 年 4 月 26 日)时,它不允许用户输入字母。我将如何创建掩码来创建自定义格式?

到目前为止,我的尝试是这样的:

<KeyboardDatePicker
    mask={[
      /\d/,
      /\d/,
      "/",
      /[a-zA-Z]/,
      /[a-zA-Z]/,
      /[a-zA-Z]/,
      "/",
      /\d/,
      /\d/
    ]}
    format="dd/MMM/yyyy"
    placeholder="DD/MMM/YYYY"
    label="Date of birth"
    openTo="year"
    views={["year", "month", "date"]}
    value={selectedDate}
  />

标签: reactjsformsmaterial-uimaskdate-formatting

解决方案


掩码只能接受string,所以在您的情况下,正则表达式数组将不起作用。

还有另一个标志refuse可以用来拒绝输入中的模式。我们可以利用它来允许字母输入。

这是代码框:

https://codesandbox.io/s/material-ui-pickers-keyboard-birthdate-forked-hmtgv?file=/src/index.js

const refusePattern = () => {
    return /[^a-zA-Z0-9]+/gi; //reject the pattern which is not a-z, A-Z and 0-9
};

<KeyboardDatePicker
   ...
   refuse={refusePattern()}

/>

推荐阅读