I use the below block of code to validate Unique username.
function validateRepositoryUnique($field, $list, &$valid) {
if ( preg_grep('/^'.preg_quote($field->value).'$/i', $list) == -1) {
$valid = false;
$field->valid = false;
$field->error = '"' . $field->value . '" already exists.';
return false;
}
return true;
}
Example.
$filed->value = "test";
$list = array('test','test1','Test');
However I passed "test" in $filed->value. the Boolean kept showing value bool(true)
when i did var_dump(validateRepositoryUnique($field, $list, &$valid));
And whatever I have inputted "test", "abc", "a", the Boolean kept return value bool(true)
.
My intention is when text found in array, it will return the $valid
's value to false and print out the error.
Apology for my bad English and my basic knowledge of PHP programming language.
preg_grep does not return -1 if it finds no results. If returns an array of what it found. You can see the output in the example below.
Notice that I somewhat rewrote your function.
function validateRepositoryUnique($field, $list, &$valid) {
$preg = preg_grep('/^'.preg_quote($field->value).'$/i', $list) ;
var_dump($preg);
echo "\n";
if ( count($preg) == 0 ) {
$valid = false;
$field->valid = false;
$field->error = '"' . $field->value . '" already exists.';
return false;
}
return true;
}
$v;
$list = ['square', 'round', 'long'];
$f1 = new stdclass;
$f1->value = 'round';
$result = validateRepositoryUnique($f1, $list, $v);
var_dump($result);
echo "\n";
$f1->value = 'grass';
$result = validateRepositoryUnique($f1, $list, $v);
var_dump($result);
echo "\n";
$f1->value = 'triangle';
$result = validateRepositoryUnique($f1, $list, $v);
var_dump($result);
echo "\n";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.