How to "Validate" Human Names in Cakephp

How to Validate Human Names in CakePHP?

I agree with the other comments that validating a name is probably a bad idea.

For virtually everything you can think of to validate, there will be someone with a name that breaks your rule. If you're happy with the idea that you're going to be blocking real people from entering their names, then you can validate it as much as you like. But the more validation rules you put in, the more likely you are to find a real person who can't sign in.

Here's a link to a page which describes some of the obvious (and not so obvious) things which people try to validate, which can trip them up:

http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

If you want to allow anybody onto your site, then the best you can really hope for is to force a maximum field length to fit the space you've allocated in your database. Even then you're going to annoy someone.

How can I do alphanumeric with space regex model validation in CakePHP?

You have to be careful validating names... what about:

  • Donalg McDonald <- capital in the middle of a word
  • Donalg Fooble-Whiffery <- hyphenated
  • Donalg Déénsbnérry-McDonald Sr. 3rd <- you get the idea

To validate names in the format you specified:

/[A-Z][a-z]+ [A-Z][a-z]+/

Being a bit more lenient:

/([\w.-]+ )+[\w+.-]/

Cakephp Special Character Validation

you can define Custom Regular Expression Validation

public $validate = array(
'login' => array(
'rule' => '/^[\W]+$/',
'allowEmpty' => false,
'message' => 'Enter Special character only.'
)
)
// '/^[\w.-]+$/' this will allow only special character.

regex to validate first name excluding @()&

If your intention was to allow special characters (other than those four) anywhere in the string, then your pattern is wrong.

I'll break down your pattern to walk you through what it does:

  • ^ - The match must begin at the start of a line (or entire string).
  • [^0-9\@\(\)\&] - Match any single character which is not a number, an @, a parenthesis, or an ampersand. I'm pretty sure the slashes here are superfluous, by the way. The ones before the @ and & characters almost certainly are, since those characters aren't ever special inside regexes. The ones before the ( and ) might be needed, since those characters are the subpattern delimiters, but I think they're still unneeded here since they're inside a character class.
  • [a-zA-Z\s]* - Match any lower or uppercase character between A and Z, or any whitespace character, like a space (this is what \s does). The * means you can match as many of these characters as there are in a row, or no characters if none of them exist in this position.
  • $ - The match must end at the end of the line (or entire string).

In short, you're only excluding those four special characters from the first character of your string, but you're exluding all special characters as any character after the first.

If you want to allow any character, except those four, in any position in the string, then you should use this as your pattern:

/^[^0-9@&()]*$/

With all of that said, I think you might be overcomplicating things a bit. It's sort of a matter of opinion, but I try to only use regular expressions when there is no other way to do something, since they can be a bit hard to read (this question is a good example of that).

What I would suggest is that you just use str_replace to remove the four characters you're disallowing, and check the resultant string against your original input:

if($input === str_replace(array('@', '&', '(', ')'), '', $input) {
// process valid input
} else {
// handle invalid input
}

The str_replace call will take your original string and replace any value in the search array, array('@', '&', '(', ')'), and remove it (technically, "replace" it with nothing). If the two strings match after that, then none of the invalid characters were present, and your input is valid.

Since you're using parentheses as items within the array, it might be more readable to separate the elements onto their own lines:

$chars_to_remove = array(
'@',
'&',
'(',
')'
);
if ($input === str_replace($chars_to_replace, '', $input)) {
// process valid input
} else {
// handle invalid input
}

Checking if at least one field is set using CakePHP 3 validation

The provided answers all did not work 100%, so I am going to post what I have come up with. I am using conditional validation as described in the CakePHP 3 docs.

CustomersTable.php:

public function validationDefault(Validator $validator)
{
$validator->notEmpty('name', __("Required when prename and lastname is empty."), function ($context) {
return !$context['data']['prename'] && !$context['data']['lastname'];
});

$validator->notEmpty('prename', __('Required when company or lastname is empty.'), function ($context) {
return !$context['data']['name'];
});

$validator->notEmpty('lastname', __('Required if company or prename is empty.'), function ($context) {
return !$context['data']['name'];
});

return $validator;
}

This approach correctly validates the data when it is submitted. However, some browsers say that those fields have to be filled because they are required. To avoid that, we have to define the fields as required => false:

add.ctp view file:

echo $this->Form->input('prename', [
'label' => ['text' => __('Prename (*): ')],
'required' => false,
]);

echo $this->Form->input('lastname', [
'label' => ['text' => __('Lastname (*): ')],
'required' => false,
]);

echo $this->Form->input('name', [
'label' => ['text' => __('Company name (*): ')],
'required' => false,
]);

How can I convert validation error field names to input names in CakePHP?

That's because that's the way the $validationErrors array is formatted. To obtain the output you want you will have to loop through, there's no way around it.

foreach ($this->User->validationErrors as $field => $error) {
$this->User->validationErrors["data[User][$field]"] = $error;
unset($this->User->validationErrors[$field]);
}

I would suggest instead passing all errors to json_encode(). $this->validationErrors is a combined list of all model validation errors for that request available on the view (compiled after render). You should move your display logic (echoing json) into your view, and loop through it there.

in the view

$errors = array();
foreach ($this->validationErrors as $model => $modelErrors) {
foreach ($modelErrors as $field => $error) {
$errors["data[$model][$field]"] = $error;
}
}
$response['errors'] = $errors;
echo json_encode($response);

This would output something like this:

{
"success":false,
"errors": [
"data[User][username]": "This is not a valid e-mail address",
"data[User][password]": "This is not a valid password",
"data[Profile][name]": "Please fill in the field"
]
}

How to detect a name, a number and comment (optional) in a string with PHP?

Let me present you a very brittle solution that works with your example string:

^ *+([A-Za-z ]*[A-Za-z]) *+(\+\d+)?+ *+(?|,?+ *+\( *+(.*\S) *\) *|,?+ *+(.*\S) *)?$

Name will be in capturing group 1. Number (sign included) will be in capturing group 2. Comment will be in capturing group 3.

Currently, the assumption is that name can only contain space and English alphabet.

Another assumption is that only space (ASCII 32) is recognized as spacing character.

Demo (Please ignore the flags, they are for demonstration purpose only).

Model Validation in CakePHP

Check the syntax on maxLength. It should be camel cased. Because you used all lower case, it cannot find the correct method.

You wrote:

'rule' => array('maxlength', 25),

It should be

'rule' => array('maxLength', 25),

See: http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::maxLength

Also, you are writing the rule with a custom name like this:

'address' => array(
'maxLength' => array(
'rule' => array('maxLength', 255),
'message' => "Your email address can't contain more than %d characters.",
'on' => 'update',
),
),

Try changing it to:

'address' => array(
'rule' => array('maxLength', 255),
'message' => "Your email address can't contain more than %d characters.",
'on' => 'update',
),


Related Topics



Leave a reply



Submit