Aug 5, 2012

Email validation through MySQL triggers and signals

Did some research and found out that MySQL provides triggers and signals. Triggers allow you to run some code when an certain event occurs, and Signals allow you to raise exceptions in your code.

Here is a SQL script to show you how it is done:

CREATE SCHEMA IF NOT EXISTS `test` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;

USE `test`;

CREATE TABLE IF NOT EXISTS `test`.`entity_email` (
    `emailID` INT NOT NULL,
    `email` VARCHAR(64) NOT NULL,
    PRIMARY KEY (`emailID`) )
ENGINE = InnoDB
COMMENT = "Generic Email table";

DELIMITER $$

USE `test`$$
CREATE TRIGGER `trg_entity_email_insert` BEFORE INSERT ON `test`.`entity_email` FOR EACH ROW

BEGIN
    IF NOT (SELECT NEW.email REGEXP '$[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$') THEN
        -- bad data
        SIGNAL SQLSTATE '40000';
    END IF;
END$$
CREATE TRIGGER `trg_entity_email_update` BEFORE UPDATE ON `test`.`entity_email` FOR EACH ROW

BEGIN
    IF NOT (SELECT NEW.email REGEXP '$[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$') THEN
        -- bad data
        SIGNAL SQLSTATE '40000';
    END IF;
END$$


DELIMITER ;

Now MySQL will perform e-mail validation EVERY time you insert or edit the record. If it doesn't match, it will fail (MySQL outputs an "Unhandled user-defined exception condition" as the error message).

Hope this helps!

6 comments:

  1. Thanks a lot! this really help me, There is a tiny mistake in "REGEXP '$["
    It should be "REGEXP '^[" with ^ instead of $, this way works like a charm

    ReplyDelete
  2. I appreciated your work very thanks Verifications IO

    ReplyDelete
  3. how to get an out put as "wrong email" instead of "Unhandled user-defined exception condition"

    ReplyDelete
  4. Email Validation and Verification, Email Checker and Bulk Verify Tool. Using DeBounce remove invalid, disposable, spam-trap, syntax and deactivated emails. email list cleaning service

    ReplyDelete
  5. DeliverBility offers very fast and simple email verification online service that validates your email lists to check for invalid or undeliverable emails so that you can maximize your marketing campaign potential.

    ReplyDelete
  6. A good mysql email checker. This script has saved me a lot of stress

    ReplyDelete

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!