Creating Unique Rules

Hi all
I’m trying to create a rule to that an email address record that is unique - very simply in CakePHP2

		'primary_email' => [
			'email' => [
				'rule' => ['email'],
				'message' => 'Supply a valid email address.',
				'allowEmpty' => true
            'isUnique' => [
                'rule' => ['isUnique'],
                'message' => 'Another member with this email address already exists.'

I’m finding that in CakePHP4, when I clear the email address field as “blank”, the validation is triggered because the “blank” value is not unique. I’ve read about “allowMultipleNulls” but I’m guessing as it’s not a “null” - this isn’t working. Do I need to set the field as “null” if blank?

Creating Unique Field Rules

Yes, that should do it. Did you try?

Not yet. I’m guessing that it will be something in BeforeSave, where if the field is empty then set as null?

While I’m generally loving CakePHP4 - more than once I find myself thinking “It was actually easier in v2…”


You can do in object entity this setter

protected function _setEmail($value)
        if ($value == '') {
            $value = null;
        return $value;

then rule will work perfectly

            ['message' => __('This email is alredy in use!'), 'allowMultipleNulls' => true]

1 Like

perfect indeed

Thanks a lot

1 Like

You can add Email validation in CakePHP 4.x

->add('email', [
		'message'=>__('Please enter email'),
		'message'=>__('Please enter valid email'),
		'message'=>__('This email already exist')
1 Like