在蚂蚁设计中输入限制字符

时间:2019-09-20 10:28:10

标签: javascript reactjs typescript antd

我有带有输入的蚂蚁设计表格,我需要限制一些要写在输入中的字符。

<Form.Item
              {...formItemLayout}
              label={this.props.intl.formatMessage({ id: 'customer.form.zipCode' })}
            >
              {getFieldDecorator('zip_code', {
                validateTrigger: 'onBlur',
                initialValue: this.props.addressFormDefaults ? this.props.addressFormDefaults.zip_code : '',
                rules: [
                  {
                    transform: (value) => typeof value === 'string' ? value.trim() : undefined,
                    required: true, message: this.props.intl.formatMessage({ id: 'validation.requiredField' }),
                  },
                ],
              })(
                <Input
                  type="number"
                  size="large"
                  className={this.props.useSmartForm ? `${this.props.smartFormClassInstance} ${SMARTFORM_CLASS.ZIP}` : undefined}
                  form={this.props.formId}
                  disabled={this.props.formDisabled}
                />,
              )}
            </Form.Item>

因此理想的解决方案是添加一些按键事件并像

一样进行验证
<Input
  type="number"
  onKeyDown={(event) => {
    // some validation;
    if (someValidation()) {
      return true;
    }
    return false;
  }}
/>;

但根据ts定义

onKeyPress?: KeyboardEventHandler<T>;
type React.KeyboardEventHandler<T = Element> = (event: KeyboardEvent<T>) => void

其void函数。当我尝试返回false时,它不会受到限制。 ant设计受到某种程度的阻碍,并且不会从此回调中返回值。 用户甚至都不应该写它。

alslo我不使用任何状态,仅使用事件的初始值。

有解决方案如何添加经典的onKeyPress,onKeyDown等输入事件,而不是蚂蚁设计事件吗?

thx

2 个答案:

答案 0 :(得分:1)

前几天,我在Antd输入上实现了类似的功能,并使用了另一个答案的常规功能。这可以按预期工作,只需使用React.KeyboardEvent作为参数,为要允许的任何字符编写一个正则表达式即可:

const onKeyPress = (e: React.KeyboardEvent) => {
   const specialCharRegex = new RegExp("[a-zA-Z0-9@.' ,-]");
   const pressedKey = String.fromCharCode(!e.charCode ? e.which : e.charCode);
   if (!specialCharRegex.test(pressedKey)) {
      e.preventDefault();
      return false;
   }
}

更新:您使用的是哪个版本的AntD,在哪里可以看到该定义?我正在使用3.23.1,并且InputProps接口没有为onKeyPress明确定义。但是Input组件会将所有其他道具转发到它在return语句中呈现的基本HTML输入,因此不应存在任何类型冲突。

通常,事件处理程序不返回显式值,而是通过default true返回,并且可以返回false来指示事件已被取消,就像上面的函数一样。关于为什么返回类型为void的函数为何允许返回false,这是TypeScript故意造成的,this answer对此进行了深入解释。

答案 1 :(得分:0)

此外,我只是使用具有antd设计的正则表达式格式。

<Form.Item>
    {getFieldDecorator('mobile', {
        rules: [
            {
                required: true,
                pattern: new RegExp("^[0-9]*$"),
                message: "Wrong format!"
            },
        ],
    })(
        <Input
            className="form-control"
            type="text"
            placeholder="Phone number"
        />,
    )}
</Form.Item>