htmlreactjsregexpostal-code

Input regex for UK postcodes constantly invalid


I'm attempting to add the pattern validation to my input using regex ^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$ and upon entering a postcode of form AB1 2CD which I would expect to be valid, I'm constantly getting an invalid message...

enter image description here

const REGEXES = {
    postcode: /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/,
    ...
};

const ADDRESS_FORM_FIELDS = [
    ...,
    {
        name: 'postcode',
        required: true,
        label: 'Postcode',
        type: 'text',
        pattern: REGEXES.postcode
    }
];

const MyForm = () => {
    
   ...
   
   return (
     <form ...>
        {
            ADDRESS_FORM_FIELDS.map(({name, required, label, type, ...rest}) => (<>
               <label for={name}>{label}{required ? ' *' : ''}</label>
               <input {...{name, type, required, placeholder: label, ...rest, value: addressValues[name], onChange: handleAddressFormChange}} />
                </>))
            }
     </form>
  )
}

Solution

  • The problem is that you are using a normal regular expression (a RegExp object) which gets converted to a string to be passed to the pattern attribute.

    pattern.
    ...
    No forward slashes should be specified around the pattern text.
    ...

    The toString() method of the RegExp will create something like /.../flags but the pattern attribute expects the "inside" part of the regular expression, not the / parts.

    So you can use the .source property that extracts just that.

    So,

    const ADDRESS_FORM_FIELDS = [
        ...,
        {
            name: 'postcode',
            required: true,
            label: 'Postcode',
            type: 'text',
            pattern: REGEXES.postcode.source
        }
    ];