Skip to content

Instantly share code, notes, and snippets.

@wilr
Last active September 24, 2015 20:17
Show Gist options
  • Save wilr/803665 to your computer and use it in GitHub Desktop.
Save wilr/803665 to your computer and use it in GitHub Desktop.
A SilverStripe Email Field which enforces unique email addresses.
<?php
/**
* UniqueEmailField extends the built in {@link EmailField} but add's an additional check
* to the validation to ensure a member doesn't already exist which the email given.
*
* @author Will Rossiter <http://twitter.com/wilr>
*/
class UniqueEmailField extends EmailField {
function validate($validator) {
$valid = parent::validate($validator);
if($valid) {
// only do another look up if it will pass validation
if($member = Member::currentUser()) {
if($this->value == $member->Email) return true;
}
if(DB::query("SELECT COUNT(*) FROM Member WHERE \"Email\" = '". Convert::raw2sql($this->value) ."'")->value() > 0) {
$validator->validationError(
$this->name,
_t('UniqueEmailField.UNIQUEVALIDATION', "A member already exists which that email address."),
"validation"
);
return false;
}
}
return $valid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment