Search code examples
regexvalidationantd

It's possible to add a multiple regex rule with antdesign?


I am trying to validate a NIF/NIE in the same input.

I am trying to get an error if the input doesn't match both regex.

 <Form.Item
              name="nifnie"
              label="NIF/NIE"
              rules={[
                { required: true, message: "NIF/NIE is mandatory." },
                {
                  pattern:
                    /^[XYZ][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/i ||
                    /^[0-9]{8}[TRWAGMYFPDXBNJZSQVHLCKE]$/i,
                  message: "Not a valid format.",
                },
              ]}
            >
              <Input />
            </Form.Item>

Solution

  • Instead of using 2 patterns, you can write it using a single pattern and an alternation between [XYZ][0-9]{7} and [0-9]{8} as the rest of both patterns is the same:

    /^(?:[XYZ][0-9]{7}|[0-9]{8})[TRWAGMYFPDXBNJZSQVHLCKE]$/i
    

    Or

    new RegExp('^(?:[XYZ][0-9]{7}|[0-9]{8})[TRWAGMYFPDXBNJZSQVHLCKE]$', 'i')