0

I am trying to create a constraint for a table, concerning on of its columns. Lets say there is a Username-Passwords table called "users" and I want to add a minimum length value to the userName column to always be above 2.

CREATE TABLE IF NOT EXISTS users(
    userName VARCHAR(255) NOT NULL UNIQUE, 
    password VARCHAR(255) NOT NULL)
ENGINE=INNODB;

I have tried this

ALTER TABLE `users` ADD CONSTRAINT `min_username_field` CHECK ( LENGTH(`userName`) > 2 );

and this

ALTER TABLE `users` ADD CONSTRAINT `min_username_field` CHECK ( CHAR_LENGTH(`userName`) > 2 );

but non of them return some sort of error when I INSERT a username with 0 or 1 characters.

EDIT: Found Solution with a trigger

CREATE TRIGGER username_trigger BEFORE INSERT ON `users`
FOR EACH ROW
  BEGIN
    DECLARE usernameLength INT;
    SET usernameLength = (SELECT LENGTH(NEW.userName));
    IF (usernameLength) < 3 THEN
      SIGNAL SQLSTATE '45000' set message_text='Error: Username must consist of 3 characters at least!!!';
    END IF;
  END;
ceid-vg
  • 323
  • 2
  • 9
  • 21

0 Answers0