I am working on a database building for a huge XML engine. This will store data of many service providers and Hotel suppliers. I came with a need to validate fields at three levels : Client side, Server side and Validation in database; for the purpose of security.
As right now I am designing and developing database, I came with a thought to impose rules to maximum columns. This will provide a validation at database level.
May this post help you in some regard.
1) First create rule.
2) bind rule to table's column.
Create Rule:
Let us create rule for Email validation
CREATE RULE Email_Rule
AS CHARINDEX(' ',LTRIM(RTRIM(@Email))) = 0
-- No embedded spaces
AND LEFT(LTRIM(@Email),1) <> '@'
-- '@' can't be the first character of an email address
AND RIGHT(RTRIM(@Email),1) <> '.'
-- '.' can't be the last character of an email address
AND CHARINDEX('.',@Email,CHARINDEX('@',@Email)) - CHARINDEX('@',@Email) > 1
-- There must be a '.' after '@'
AND LEN(LTRIM(RTRIM(@Email))) - LEN(REPLACE(LTRIM(RTRIM(@Email)),'@','')) = 1
-- Only one '@' sign is allowed
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@Email)))) >= 3
-- Domain name should end with at least 2 character extension
AND (CHARINDEX('.@',@Email) = 0 AND CHARINDEX('..',@Email) = 0)
-- can't have patterns like '.@' and '..'
Bind this rule to Email field of Address table:
EXEC sp_bindrule 'Email_Rule', 'Address.Email'
You can also drop rules:
drop rule Email_Rule
But before droping rule you MUST unbind rule from any column which it is attatched to:
EXEC sp_unbindrule 'Address.Email'
It is a tough task in a large database to find which table's which column the rule is bound. There is a very easy query to find this:
SELECT name FROM sysobjects WHERE name = 'phone_rule' AND type = 'R'

No comments:
Post a Comment