Hướng dẫn username validation in php

I want username validation in php. I just want to allow user to type ABC[ English characters] only. I do not want allow to user to type []{}()//,.<>*~``^.

I have this code :

 if(preg_match('/^[0-9]{2,}$/', $_POST['username'])){
        $username_err = "
type alphanumaric in first name only
";

Hướng dẫn username validation in php

EricLavault

7,8942 gold badges22 silver badges39 bronze badges

asked Jan 11, 2020 at 7:09

Hướng dẫn username validation in php

6

your regular expression is wrong in this case, simply add this regular expressions

if(preg_match('/^[a-zA-Z0-9]*$/', $_POST['username']))

if you want to not allow the number too test this one:

if(preg_match('/^[a-zA-Z]*$/', $_POST['username']))

answered Jan 11, 2020 at 7:40

Hướng dẫn username validation in php

2

  • Biểu thức chính quy là chuỗi miêu tả một bộ các chuỗi khác, theo những quy tắc, cú pháp nhất định
  • Dùng chuẩn hóa dữ liệu đầu vào hoặc tìm kiếm theo một định dạng mẫu cho trước.

Ví dụ:

^([A-Z]){1}([\w_\.!@#$%^&*()]+){5,31}$

KIỂM TRA DỮ LIỆU BẰNG BIỂU THỨC CHÍNH QUY

  • Sử dụng hàm preg_match để kiểm tra khớp dữ liệu
  • Thông qua việc kiểm tra để kết luận và thông báo cho người dùng nếu dữ liệu đầu vào không đúng định dạng mình quy định trước.
 $pattern = "/^([A-Z]){1}([\w_\.!@#$%^&*()]+){5,31}$/";
$subject = "Cuongsb";
if(!preg_match($pattern,$subject))
   echo  "Mật khẩu bạn vừa nhập không đúng định dạng ";

BIỂU THỨC CHÍNH QUY THƯỜNG DÙNG

1. Kiểm tra định dạng username

  • Username  bao gồm các ký tự chữ cái, chữ số, dấu gạch dưới, dấu chấm
  • Độ dài 6-32 ký tự
  /^[A-Za-z0-9_\.]{6,32}$/

2. Kiểm tra định dạng password

  • Mật khẩu bao gồm các ký chữ cái, chữ số, ký tự đặc biệt, dấu chấm
  • Bắt đầu bằng ký tự in hoa
  • Độ dài 6-32 ký tự
/^([A-Z]){1}([\w_\.!@#$%^&*()]+){5,31}$/

3. Kiểm tra định dạng Email

  • Chứa các ký tự chữ cái, chữ số, dấu chấm, gạch dưới
  • Ký tự @
  • Nhóm ký tự trước @ có 6-32 ký tự
  • Nhóm ký tự sau @ là domain một hoặc nhiều cấp
 ^[A-Za-z0-9_.]{6,32}@([a-zA-Z0-9]{2,12})(.[a-zA-Z]{2,12})+$

GHI NHỚ

  • Biểu thức chính quy là biểu thức tạo ra định dạng mẫu của đối tượng cho trước.
  • Biểu thức chính quy được xây dựng phục thuộc vào yêu cầu của từng hệ thống
  • Hàm preg_match giúp chúng ta kiểm tra dữ liệu có khớp với biểu thức chính quy hay không

Url Link

http://hocweb123.com/validation-form-bang-bieu-thuc-chinh-quy.html

Home  »  How To Guides  »  PHP   »   How to Validate First and Last Name using Regular Expression in PHP

Nội dung chính

  • How do you validate user inputs in PHP?
  • Can validation be done in PHP?
  • What is validation rule in PHP?
  • Which are the types of validation in PHP?

When you allow the user to submit data on the server, it’s a good idea to validate data before further processing. A name field is a common form filed for a web application. Here we will show how you can validate the name filed to check whether the user provides their first and last name.

The Regular Expression (REGEX) is the easiest way to validate full name format in PHP. You can easily validate first and last name using regular expression in PHP. Use PHP preg_match() function to perform a regular expression match.

The following example code uses preg_match() function and simple REGEX for name validation in PHP.

preg_match("/^([a-zA-Z' ]+)$/","Given_Name");

Usage:

if(preg_match("/^([a-zA-Z' ]+)$/",$givenName)){
    echo 
'Valid name given.';
}else{
    echo 
'Invalid name given.';
}

I have been creating some validation for a signup form, and I have come across an error when validating the user's name.

I have used an input of "Test" for both firstname and lastname and I still get an error when it should allow the input, since !preg_match('/^[a-z]*$/i', $value) should allow both lower and uppercase characters?

Also the error that I get seems to be only triggering for the firstname and not last name.

 $value){
            if($field === 'firstname' || $field === 'lastname' && !preg_match('/^[a-z]*$/i', $value)){
                $errors[] = "{$field} has invalid characters please try again.";
                echo $error;
            }         
        }
}
?>

asked Feb 9, 2018 at 17:33

3

You are missing brackets around your "OR" condition. The "AND" takes precedence over "OR".

if(($field === 'firstname' || $field === 'lastname') && !preg_match('/^[a-z]*$/i', $value)){
     $errors[] = "{$field} has invalid characters please try again.";
}

NB: In your code above, you have an "undefined variable" : $error.

answered Feb 9, 2018 at 17:37

SyscallSyscall

18.3k10 gold badges33 silver badges49 bronze badges

0

I recommend that:

  1. you make your conditional more direct/brief/DRY with: in_array($key,['firstname','lastname']) instead of two separate checks.

  2. you avoid the unnecessary use of a regex function when there is a non-regex function that was designed to perform the same task: !ctype_alpha($value)

This is what the implementation could look like:(Demo)

$_POST=['submit'=>'','firstname'=>'legit','lastname'=>'n0tl3g!t'];

$errors=[];
foreach($_POST as $key=>$value){
    if(in_array($key,['firstname','lastname']) && !ctype_alpha($value)){
        $errors[]="$key field contains invalid value: $value";
    }
}
var_export($errors);

Output:

array (
  0 => 'lastname field contains invalid value: n0tl3g!t',
)

As for improving the UX of your application, I recommend using HTML5 validation in your form to prevent the submission of invalid field values like so...


answered Feb 14, 2018 at 2:35

mickmackusamickmackusa

39k11 gold badges76 silver badges113 bronze badges

How do you validate user inputs in PHP?

PHP has filter_var() function to validate variables. We can set it's second parameter to different values and use it to validate emails, URLs, integers, booleans, etc. This function returns false on failure or invalid input. We can simply validate an email using filter_var() function and FILTER_VALIDATE_EMAIL flag.

Can validation be done in PHP?

Form Validation is a necessary process before the data entered in the form is submitted to the database. This is done to avoid unnecessary errors. In PHP Form validation, the script checks for data in respective fields based on the rules set by the developer, and returns an error if it does not meet the requirements.

What is validation rule in PHP?

There are two types of validation are available in PHP. They are as follows − Client-Side Validation − Validation is performed on the client machine web browsers. Server Side Validation − After submitted by data, The data has sent to a server and perform validation checks in server machine.

Which are the types of validation in PHP?

Client-Side Validation: This type of validation is done on the web browser of the client machine. Server-Side Validation: The data on submission is then sent to the server machine to perform validation checks there.