validation the max length of ant design InputNumber in react

Viewed 13242

I have an antd InputNumber in Form.Item in a react project. My validation for this input is checking the length of input value.

This is my code:

render() {
    return (
      <Form.Item
        label="Value"
        name="numberValue"
        rules={[
          {
            pattern: /^(?:\d*)$/,
            message: "Value should contain just number",
          },
          {
            maxLength: 50,
            message: "Value should be less than 50 character",
          },
        ]}
        validateTrigger="onBlur"
      >
        <InputNumber
          onChange={(value) => {
            this.props.setValue(value);
          }}
        />
      </Form.Item>
    );
  }

I have two problems:

  1. I want to show the Value should contain just number messages when user enter non numeric character. But this message doesn't show at all.

  2. I want to show the Value should be less than 50 character message, when user enter the number/value with more than 10 character. But now, with entering the first character, this message will be shown!

4 Answers

Depends on which validation library are you using.

InputNumber max is Number.MAX_SAFE_INTEGER, so maybe use a simple <Input> with a pattern matcher:

  render() {
    return (
      <Form.Item
        label="Value"
        name="numberValue"
        rules={[
          {
            pattern: /^(?:\d*)$/,
            message: "Value should contain just number",
          },
          {
            pattern: /^[\d]{0,50}$/,
            message: "Value should be less than 50 character",
          },
        ]}
        validateTrigger="onBlur"
      >
        <Input
          onChange={(value) => {
            this.props.setValue(value);
          }}
        />
      </Form.Item>
    );
  }
<InputNumber 
    type="number" 
    placeholder="00" 
    parser={(value) => { 
        return value.substring(0, 2)
    }} 
/>

It will allow to wright only 2 digit. If you want to allow more than just change substring value 2

The easiest way to define the length of the input:

<Form.Item
    label="Value"
    name="numberValue"
    rules={[
      {
        pattern: /^(?:\d*)$/,
        message: "Value should contain just number",
      },
      {
        max: 50,
        message: "Value should be less than 50 character",
      },
    ]}
    validateTrigger="onBlur"
  >
    <InputNumber
      onChange={(value) => {
        this.props.setValue(value);
      }}
    />
  </Form.Item>

You use maxlength in <Input /> and type='number' must in rules

<Input maxLength={50}
    onChange={e => getValue(e.target.value)}
    rules={[{ type: 'number' }]} />
Related