Question

So far I have been quite impressed by out of the box features provided by Prestashop but this thing really let me down: If someone wants to register on the site or do a guest check out he can put anything as his name. Anything includes things like "---", all spaces, "*" etc. There is no validation provided here and this is really annoying.

I have tried to modify the processSubmitAccount method in website\controllers\front\AuthController.php to use the Validate::isName() method but this does not help at all. It lets the users put all the strange character in the name field. I tried to create another method inside the Validate class:

public static function isHumanName($name)
{    
 return preg_match('/^[A-Za-z]+$/', $name);
}

but for some reason this simple pattern does not work. All I want to be able to do is allow names like "FirstName MiddleName" having only one space chracter at a time and not at the start of the name. My php and regex skills are minimal and this is all I have come up with so far.

EDIT: Acceptable names would be:

  1. FirstName
  2. FirstName Second Third Fourth Fifth
  3. Names can be case insensitive.

After reading comments, I think I will give up on validating Addresses so striking out below para.

Besides name I want to validate addresses and phone numbers. Addresses can have numbers in addition to letters while phone numbers can only have numbers. I guess if the problem with validating names is solved then I would be able to do it for address and numbers as well.

I would appreciate if someone can put me in right direction.

PS: It is a separate debate whether enforcing a naming policy is right or wrong. *DISCLAIMER: The answer to this question does not mean that readers use the same thing in their production applications for validating names.*

Was it helpful?

Solution

preg_match('/^[A-Za-z]+\s[A-Za-z]+$/', $name);

would match:

FirstName MiddleName

Example: http://regex101.com/r/lE5gW4

EDIT:

Ok, this conforms more closely to what the OP is requesting.

Regex:

^([A-Z][A-Za-z]+) (?:([A-Z][A-Za-z.]+) )?([A-Z][A-Za-z]+)$

This matches the following variations..

FirstName M. LastName
FirstName LastName
FirstName MiddleName Lastname

Working regex example:

http://regex101.com/r/nG1vN5

Note: and if you wanted to allow ' in the name such as in O'Brien or any other characters, you could just add them into the character sets. ie- ([A-Z][A-Za-z.']+)

Php example:

$name = "FirstName M. LastName";

$truefalse = preg_match('/^([A-Z][A-Za-z]+) (?:([A-Z][A-Za-z.]+) )?([A-Z][A-Za-z]+)$/', $name);

echo $truefalse;

Output:

1

Working php example:

https://eval.in/90720

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top