Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validation the max length of ant design InputNumber in react

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!

like image 347
Zahra Talebi Avatar asked Mar 03 '23 03:03

Zahra Talebi


2 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>
    );
  }
like image 167
Robert Kovacs Avatar answered Apr 28 '23 05:04

Robert Kovacs


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>
like image 40
adelbbj Avatar answered Apr 28 '23 04:04

adelbbj