I have a field in my database that is a phone number i want to make it only accept exact 9 numbers
Mysql version: 5.7.31
I have a field in my database that is a phone number i want to make it only accept exact 9 numbers
Mysql version: 5.7.31
Add according CHECK Constraint.
As column constraint:
CREATE TABLE my_table (
...
phone_number INT
NOT NULL
CHECK (phone_number BETWEEN 100000000 AND 999999999),
... );
or as table constraint:
CREATE TABLE my_table (
...
phone_number INT
NOT NULL,
CONSTRAINT phone_9_digits
CHECK (phone_number BETWEEN 100000000 AND 999999999),
... );
The constraint deals with one column only - so column constraint type is preferred.
How can i do this to a existing table?
Alter column definition or table definition. For example,
ALTER TABLE my_table
CHANGE COLUMN phone_number
phone_number INT
NOT NULL
CHECK (phone_number BETWEEN 100000000 AND 999999999);
If you use old MySQL version which does not support CHECK constraints then use triggers pack.
CREATE TRIGGER tr_bi_check_phone_for_9digits
BEFORE INSERT -- and the same for BEFORE UPDATE
ON my_table
FOR EACH ROW
BEGIN
IF NEW.phone_number NOT BETWEEN 100000000 AND 999999999 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Phone Number must have 9 digits strictly.';
END IF;
END
If phone_number
is stored as a string then checking condition phone_number BETWEEN 100000000 AND 999999999
may be replaced, for example, with
phone_number REGEXP '[0-9]{9}'
This will also allow you to store phone numbers that start from zero.
Firstly, I would not want to implement this logic in the database. It's likely to change (not every country has the same phone number layout, and even within a country, sometimes the phone number format changes). You may want to impose some kind of formatting (e.g. separating area code from number). It's generally not great to use database errors as a way of communicating formatting issues - the user interface would need to understand that logic, and it's not particularly easily managed.
But if you really want to do it in the databse, you can create a trigger to validate the input before writing it to the table, and throw an error otherwise.
Have you ever filled out a form, only to have it spit at you for not using the exact spacing, dashes, parens, etc that it expected for postal code, phone, credit card number?
For the sake of the users, I strongly recommend you allow any commonly allowed spacing, etc. Then remove extra stuff. If anything goes wrong, spit at the user form the UI, not the database. Data in the database should be cleansed by the UI.
What about the +1
(or whatever country code) that goes in front of international-savvy phone numbers? Or is your app a single country app, and will always be such?