Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Report invalid characters in string 1

Status
Not open for further replies.

PeDa

Technical User
Oct 10, 2002
227
NL
I have a form that validates each field with code like
Code:
$err='';
if (empty($input['surname'])) {$err=$err . "&bull; Surname is missing<br>";}
else{if (!preg_match("/^[\p{L}. '-]*$/u",$input['surname'])) {$err = $err . "&bull; Surname is invalid<br>";}}
then checking if $err is still empty.

I would however like to give more user-friendly feedback ('$ not allowed in surname') but cannot think how to do this (apart from checking for each illegal character individually, which is not really practicable)
 
Hi

[tt]preg_match()[/tt] has a dedicated 3[sup]rd[/sup] parameter to obtain the captured groups, but for that you will have to reverse the regular expression.
While there, I would change the function to [tt]preg_match_all()[/tt] as personally I hate when I find out about the illegal characters one submit each.
Code:
[navy]$err[/navy] [teal]=[/teal] [i][green]''[/green][/i][teal];[/teal]
[b]if[/b] [teal]([/teal][b]empty[/b][teal]([/teal][navy]$input[/navy][teal][[/teal][i][green]'surname'[/green][/i][teal]])) {[/teal] [navy]$err[/navy] [teal].=[/teal] [i][green]"&bull; Surname is missing<br>"[/green][/i][teal]; }[/teal]
[b]elseif[/b] [teal]([/teal][COLOR=orange]preg_match_all[/color][teal]([/teal][i][green]"/[^\p{L}. '-]/u"[/green][/i][teal],[/teal] [navy]$input[/navy][teal][[/teal][i][green]'surname'[/green][/i][teal]],[/teal] [navy]$match[/navy][teal])) {[/teal] [navy]$err[/navy] [teal].=[/teal] [i][green]"&bull; Surname contains invalid characters : "[/green][/i] [teal].[/teal] [COLOR=orange]implode[/color][teal]([/teal][i][green]', '[/green][/i][teal],[/teal] [navy]$match[/navy][teal][[/teal][purple]0[/purple][teal]]) .[/teal] [i][green]"<br>"[/green][/i][teal]; }[/teal]

BTW, just matter of style, but keeping the collected validation error messages in an array allows for more flexibility :
[ul]
[li]You can count them[/li]
[li]You can format them differently in case you want to log them or sent them through e-mail[/li]
[li]You can not format them in case you send them through AJAX or API[/li]
[li]Easier to rewrite later, for example if you switch to semantic HTML and display the error list in an HTML unordered list[/li]
[/ul]


Feherke.
feherke.github.io
 
Hello Feherke,

Thank you very much for this - just what I needed. Thanks also for the style tips; my little fund of PHP-knowledge just keeps growing!

PeterDa.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top