DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `pbx`.`phone_isValid`(vPhone VARCHAR(255))
BEGIN
/**
 * Check if an phone has the correct format and
 * throws an exception if it hasn't.
 *
 * @param vPhone The phone number
 */
	DECLARE vIsValid BOOL;

	SET vIsValid = vPhone IS NULL
		OR (vPhone REGEXP '^[0-9]+$'
		AND vPhone NOT REGEXP '^0+$'
		AND vPhone NOT REGEXP '^0034');

	IF NOT vIsValid THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Phone format is invalid';
	END IF;
END$$
DELIMITER ;
