简体   繁体   English

PHP - 验证注册表单

[英]PHP - Validating a registration form

How do I validate the first name to only contain az characters using php. 如何使用php验证第一个名称仅包含az字符。 I have the following at the moment: 我现在有以下内容:

 if (empty($myFirstName)) {
    echo "<p>Please enter your first name!</p>";
else if(!preg_match("/^[a-zA-Z]$/", $myFirstName)){
    echo "Your first name can only contain letters!";
}

Here's a working code : 这是一个有效的代码:

if (empty($myFirstName)) {
    echo "<p>Please enter your first name!</p>";}

else if(preg_match("/[^a-zA-Z]/", $myFirstName)){
    echo "Your first name can only contain letters!";
}

I did a little modification to the regex : I added a ^ in the group, and removed the anchors. 我对正则表达式进行了一些修改:我在组中添加了^ ,并删除了锚点。

As a result, your regex will match any character which is not a letter, and display the error message if there is a match. 因此,您的正则表达式将匹配任何非字母的字符,并在匹配时显示错误消息。

I strongly advice you to validate user input at least on server side, and on client side if you want to. 我强烈建议您至少在服务器端验证用户输入,如果需要,请在客户端验证用户输入。

For an email validation, the html filter works on client side. 对于电子邮件验证,html过滤器适用于客户端。

On server side, you can use pre-set PHP filters : 在服务器端,您可以使用预先设置的PHP过滤器:

if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo "email OK";
}

FYI, there is a regexp matching emails according to the RFC2822 standards : 仅供参考,根据RFC2822标准,有一个正则表达式匹配的电子邮件:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

May be you can use 可能你可以使用

if(! ctype_alpha($myFirstName) )
{
  //check for alphabetic inputs only
  echo "Your first name can only contain letters!";
}

Php manual Php手册

Your if is incorrect. 你的if不正确。

!preg_match("/^[a-zA-Z]$/", $myFirstName)

will only hold true if $myFirstName is not a single alpha character 只有$myFirstName not a single alpha character才会成立

to ensure that $myFirstName is not any number of alpha characters , try 要确保$myFirstName not any number of alpha characters ,请尝试

!preg_match("/^[a-zA-Z]*$/", $myFirstName)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM