javascriptreactjswordpress-gutenberggutenberg-blocksvalidator.js

How do I get validator.js to work in react?


I am fairly new to react. I have an ask that requires email validation and I found an npm package called validator.js that handles that. So I built a custom Gutenberg WordPress block with email addresses included. The code I have to call in validator seems to make the block stop rendering. Here is the code:

import { __ } from '@wordpress/i18n';
import { SimpleText, TextFormats } from '../../components/SimpleText';
import validator from 'validator';

/**
 * @typedef {Object} ContactAttrs
 * @property {'full'} align
 * @property {string} contactName
 * @property {string} contactInfo
 */

/**
 * @param {import('@wordpress/blocks').BlockEditProps<ContactAttrs>} props
 */

const isValidEmail = validator.isEmail( contactInfo );

export function ContactEdit( { className, attributes, setAttributes } ) {
    return (
        <div className={ className }>
            <div className="block-align__wrapper">
                <SimpleText
                    identifier="contactName"
                    tagName="h5"
                    value={ attributes.contactName }
                    onChange={ ( contactName ) => setAttributes( { contactName } ) }
                    placeholder={ __( 'Enter contact name' ) }
                />
                <SimpleText
                    identifier="contactInfo"
                    tagname="a"
                    value={ attributes.contactInfo }
                    allowedFormats={ TextFormats.LINK }
                    onChange={ ( contactInfo ) => setAttributes( { contactInfo } ) }
                    placeholder={ __( 'Enter email address' ) }
                />
                { isValidEmail ? <div className="error">invalid email</div> : null }
            </div>
        </div>
    );
}

when I remove the validatoir.js stuff the block works. Anything missing?


Solution

  • I think it's because contactInfo is not defined in the scope. I think it should be attributes.contactInfo. Also you need to move const isValidEmail = validator.isEmail( contactInfo ); inside ContactEdit, just put it right before return statement.