Juraj Kocan
Juraj Kocan

Reputation: 2878

Input restrict characters in ant design

I have ant design form with inputs and i need to restrict some character to be written in input.

<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>

so ideal solution would be add some of the key press events and validate it like

<Input
  type="number"
  onKeyDown={(event) => {
    // some validation;
    if (someValidation()) {
      return true;
    }
    return false;
  }}
/>;

but from the ts definition

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

its void function. when i try to return false it wont restrict. ant design is somehow retarded and dont return value from this callback. the user should not be allowed even to write it.

alslo i dont use any state, only initial value for event.

is there solution how to add classic onKeyPress, onKeyDown etc. input events, not ant design events?

thx

Upvotes: 4

Views: 12755

Answers (3)

Maruf Sharifi
Maruf Sharifi

Reputation: 81

Simply use from normalized prop of FormItem like this example

const normalizeValue = (value) => {
    // Just replace the following regex to what you wnat
    const filteredValue = value.replace(/[^a-zA-Z0-9\s]/g, '');
    return filteredValue;
   };


<FormItem label="Input" normalize={normalizeValue}>
   <Input
     name="input"
   />
</FormItem>

Upvotes: 0

Majedur
Majedur

Reputation: 3242

In addition, I am just using regex format with antd design.

<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>

Upvotes: 0

Chris B.
Chris B.

Reputation: 5763

I implemented something similar on Antd inputs just the other day with a general function from another answer. This works as expected, just write a regex for whatever characters you want to allow, using React.KeyboardEvent as the parameter:

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;
   }
}

UPDATE: What version of AntD are you using and where are you seeing that defnition? I'm using 3.23.1, and the InputProps interface has no explicit definition for onKeyPress. However the Input component forwards all additional props to the basic HTML input it's rendering in its return statement, so there shouldn't be any type conflicts.

Generally, event handlers do not return explicit values, but are by default true, and can return false to indicate the event has been cancelled, as the function above does. As to why a function with a return type of void would allow a return of false, it's a deliberate exception made by TypeScript, which is explained in-depth by this answer.

Upvotes: 7

Related Questions