MySQL Forums
Forum List  »  InnoDB

Re: check constraint
Posted by: Kareem Sedki
Date: November 15, 2008 01:23AM

Possibly the best way to validate string inputs, to my knowledge, is regular expressions.

mysql> select 'string to check' [NOT] REGEXP 'regular expression';

If there was a match in the string a value of 1 would be returned, 0 otherwise.

For digits:

select '1111111' regexp '^([0-9]+)$'; -- would return 1
select ' 1111111' regexp '^([0-9]+)$'; -- would return 0
select '1111111 ' regexp '^([0-9]+)$'; -- would return 0
select '111 1111' regexp '^([0-9]+)$'; -- would return 0

For (printing ) characters:

select 'a' regexp '^([alpha]+)$'; -- would return 1
select ' a' regexp '^([alpha]+)$'; -- would return 0
select 'a ' regexp '^([alpha]+)$'; -- would return 0
select ' ' regexp '^([alpha]+)$'; -- would return 0
select '1' regexp '^([alpha]+)$'; -- would return 0


If you are afraid there might be leading or trailing spaces, then

SET @input = LTRIM(RTRIM(@input));

Check section number 11.4.2 of the MySQL 5 manual, it is the section for regular expressions. If you use another version, find out what section it is :D.

You might use a BEFORE INSERT trigger on the table you want use this check with. The trigger should check for either of the conditions, i.e., characters only OR digits. Functions and procedures are also valid options, but it depends on what you want do. Maybe the best way is a BEFORE INSERT trigger.

Hope this helps.

Kareem

Options: ReplyQuote


Subject
Views
Written By
Posted
100469
May 09, 2007 01:54AM
39068
May 28, 2007 05:05PM
31263
June 07, 2007 07:31PM
27914
June 21, 2007 10:58PM
26130
June 28, 2007 03:02AM
24212
December 06, 2007 02:01PM
16773
October 15, 2008 04:08AM
Re: check constraint
16606
November 15, 2008 01:23AM
12171
November 15, 2008 11:09AM
18499
December 31, 2008 09:58AM
12693
January 06, 2009 03:41PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.