Hướng dẫn server side validation in php using jquery - xác thực phía máy chủ trong php bằng cách sử dụng jquery

Hướng dẫn server side validation in php using jquery - xác thực phía máy chủ trong php bằng cách sử dụng jquery

Chúng tôi sẽ học cách xác thực các biểu mẫu của bạn bằng PHP và jQuery ở cả hai bên: phía máy khách (sử dụng JavaScript với jQuery) và phía máy chủ (sử dụng PHP). Sẽ rất thú vị khi xem cách sử dụng các biểu thức chính quy để xác nhận các loại e-mail, mật khẩu khác nhau và nhiều hơn nữa.

Giới thiệu

Như bạn đã biết, chúng tôi đang hỏi bạn & nbsp; hướng dẫn của bạn có muốn xem & nbsp; trong yensdesign và như tôi đã nói với bạn, bạn không thể & nbsp; gửi cho chúng tôi thêm đề xuất và phản hồi & nbsp; trong các diễn đàn của chúng tôi.

Về các đề xuất này là về & nbsp; Cách xác nhận các biểu mẫu ở phía máy chủ bằng PHP, vì vậy trong hướng dẫn này, chúng tôi sẽ sử dụng PHP và jQuery để xác thực tất cả các trường ở cả hai phía:how to validate forms in server side using PHP, so in this tutorial we will make use of PHP and jQuery to validate all fields in both sides:

  • Phía khách hàng: Sử dụng JavaScript với & nbsp; jQuery.: Using javascript with jQuery.
  • Phía máy chủ: Sử dụng PHP.: Using PHP.

Chúng tôi sẽ sử dụng các biểu thức thường xuyên và nếu bạn không biết về chúng, bạn sẽ sớm nhận thấy sức mạnh của họ. Nhân tiện, bạn có thể kiểm tra & nbsp; Nguồn này & nbsp; để tìm hiểu thêm về các biểu thức thông thường bằng các ngôn ngữ khác nhau.

Vào cuối hướng dẫn, & nbsp; chúng tôi sẽ nhận được một ví dụ làm việc thực sự cuối cùng & nbsp; sẽ & nbsp; xác thực các trường của chúng tôi & nbsp; có / không có JavaScript được bật, nhưng & nbsp; luôn luôn sử dụng hợp lệ phía máy chủ.we will get a final real working example that will validate our fields with / without javascript enabled, but always making use of the server side validaton.

Hãy cùng đi sâu vào hướng dẫn!

Bước 1: Cách tiếp cận đầu tiên đối với bố cục XHTML

Trong trường hợp này, chúng tôi sẽ tạo một bố cục HTML đơn giản hiển thị biểu mẫu của chúng tôi. Trong một cách tiếp cận đầu tiên, HTML sẽ trông như thế này:




	
	yensdesign.com - Validate Forms using PHP and jQuery
	


	
	

Registration process

  • Invalid Name: We want names with more than 3 letters!
  • Invalid E-mail: Stop cowboy! Type a valid e-mail please :P
  • Passwords are invalid: Passwords doesn't match or are invalid!
  • Ivalid message: Type a message with at least with 10 letters
  • Congratulations! All fields are OK ;)
What's your name?
Valid E-mail please, you will need it to log in!
At least 5 characters: letters, numbers and '_'
Confirm password

Như bạn có thể thấy, chúng tôi đã tạo ra tất cả các bộ phận sẽ xuất hiện (hoặc không) trong hướng dẫn của chúng tôi. Một số bộ phận này đã giành được hiển thị là mặc định, nhưng chúng tôi sẽ thêm một số điều kiện trong PHP và CSS để có được điều này. Vì vậy, đây là những bộ phận:

  • #Container: Chứa tất cả các bộ phận: contains all divisions
  • #Error: Chứa danh sách các lỗi có thể xảy ra sau khi gửi biểu mẫu: contains a list of possible errors after submitting the form
  • #error.valid: chứa cụm từ chúc mừng: contains the “congratulations phrase” if all it’s OK
  • #CustomForm: Chứa biểu mẫu của chúng tôi & nbsp;: contains our form 
    Hướng dẫn server side validation in php using jquery - xác thực phía máy chủ trong php bằng cách sử dụng jquery

Vì vậy, bây giờ chúng tôi đã sẵn sàng bố trí XHTML của chúng tôi, hãy để thêm một số kiểu với CSS.

Bước 2: Thêm kiểu với CSS

Nó sẽ là những người nhanh chóng, chỉ cần xem & nbsp; General.css & nbsp; mã: mã:general.css code:

@CHARSET "UTF-8";
/******* GENERAL RESET *******/
html, body, div, span, applet, object, iframe, h2, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em,
font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody,
 tfoot, thead, tr, th, td {
border:0pt none;
font-family:inherit;
font-size: 100%;
font-style:inherit;
font-weight:inherit;
margin:0pt;
padding:0pt;
vertical-align:baseline;
}
body{
	background: #fff;
	line-height:14px;
	font-size: 12px;
	font-family: Arial,  Verdana, Helvetica, sans-serif;
	margin:0pt;
	cursor:default;
	overflow: hidden;
}
html,body{
	height:100%;
	text-align: center;
}
.clear{
	clear: both;
	height: 0;
	visibility: hidden;
	display: block;
}
a{
	text-decoration: none;
}
strong{
	font-weight: 700;
}
/******* GENERAL RESET *******/
h2{
	font-weight: 700;
	font-size: 18px;
	line-height: 1.2em;
	border-bottom: 1px dotted #6b9ef1;
	color: #5f95ef;
	margin-bottom: 1em;
}
/******* LOGO *******/
#logo{
	margin-top: 1em;
	display: block;
}
/******* /LOGO  *******/
/******* CONTAINER *******/
#container{
	width: 600px;
	margin: 40px auto;
	text-align: left;
}
/******* /CONTAINER *******/
/******* FORM *******/
#customForm{
	padding: 0 10px 10px;
}
#customForm label{
	display: block;
	color: #797979;
	font-weight: 700;
	line-height: 1.4em;
}
#customForm input{
	width: 220px;
	padding: 6px;
	color: #949494;
	font-family: Arial,  Verdana, Helvetica, sans-serif;
	font-size: 11px;
	border: 1px solid #cecece;
}
#customForm input.error{
	background: #f8dbdb;
	border-color: #e77776;
}
#customForm textarea{
	width: 550px;
	height: 80px;
	padding: 6px;
	color: #adaeae;
	font-family: Arial,  Verdana, Helvetica, sans-serif;
	font-style: italic;
	font-size: 12px;
	border: 1px solid #cecece;
}
#customForm textarea.error{
	background: #f8dbdb;
	border-color: #e77776;
}
#customForm div{
	margin-bottom: 15px;
}
#customForm div span{
	margin-left: 10px;
	color: #b1b1b1;
	font-size: 11px;
	font-style: italic;
}
#customForm div span.error{
	color: #e46c6e;
}
#customForm #send{
	background: #6f9ff1;
	color: #fff;
	font-weight: 700;
	font-style: normal;
	border: 0;
	cursor: pointer;
}
#customForm #send:hover{
	background: #79a7f1;
}
#error{
	margin-bottom: 20px;
	border: 1px solid #efefef;
}
#error ul{
	list-style: square;
	padding: 5px;
	font-size: 11px;
}
#error ul li{
	list-style-position: inside;
	line-height: 1.6em;
}
#error ul li strong{
	color: #e46c6d;
}
#error.valid ul li strong{
	color: #93d72e;
}
/******* /FORM *******/

Như mọi khi, chúng tôi sử dụng đoạn CSS CSS Cool của chúng tôi và thêm một số phần thú vị vào hướng dẫn cụ thể.

Chỉ cần lưu ý rằng chúng tôi đã xác định một số lớp & nbsp;.error classes that we will use in the jQuery part to make our tutorial a little more cool and friendly user  

Hướng dẫn server side validation in php using jquery - xác thực phía máy chủ trong php bằng cách sử dụng jquery

Phần tiếp theo, xác thực JavaScript!

Bước 3: Xác nhận ở phía khách hàng với jQuery

Vâng các bạn, bởi vì nó không thể là nếu không chúng tôi sẽ sử dụng & nbsp; jQuery & nbsp; để làm cho phần xác nhận ở phía khách hàng. Chúng tôi sẽ thêm / xóa một số lớp .Error để làm cho biểu mẫu của chúng tôi trực quan hơn một chút cho người dùng cuối cùng.

Vì vậy, trước hết, hãy nhớ rằng tất cả các mã sau đây sẽ nằm trong & nbsp; $ (tài liệu) .reetread () & nbsp; của jQuery và tất cả sẽ là một phần của tệp javascript có tên & nbsp; xác thực.js & nbsp; (Bản gốc, uh?) .$(document).ready() of jQuery and all will be a part of the javascript file named validation.js (original, uh?).

Vì vậy, hãy để Lừa lưu & nbsp; Tài liệu tham khảo & nbsp; đến & nbsp; một số & nbsp; Dom Elements & nbsp; mà chúng tôi sẽ thường xuyên:references to some DOM elements that we will often:

//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");

Như bạn có thể nhận thấy, tất cả các tài liệu tham khảo đều liên quan đến hình thức.

Bây giờ, hãy để xác định các chức năng xác thực của chúng tôi sẽ giúp chúng tôi trong quá trình xác thực:

  • ValidateMail (): Chúng tôi chỉ cho phép email hợp lệ!: we only allow valid emails!
  • Validatename (): Chúng tôi chỉ cho phép các tên có hơn 3 chữ cái: we only allow names with more than 3 letters
  • ValidatePass1 (): Chúng tôi chỉ cho phép mật khẩu có ít nhất 5 ký tự: we only allow passwords with at least 5 characters
  • ValidatePass2 (): Chúng tôi chỉ cho phép nếu mật khẩu bằng nhau: we only allow it if passwords are equal
  • Validatemessage (): Chúng tôi chỉ tin nhắn với hơn 10 chữ cái: we only messages with more than 10 letters

function validateName(){
	//if it's NOT valid
	if(name.val().length < 4){
		name.addClass("error");
		nameInfo.text("We want names with more than 3 letters!");
		nameInfo.addClass("error");
		return false;
	}
	//if it's valid
	else{
		name.removeClass("error");
		nameInfo.text("What's your name?");
		nameInfo.removeClass("error");
		return true;
	}
}
function validatePass1(){
	var a = $("#password1");
	var b = $("#password2");

	//it's NOT valid
	if(pass1.val().length <5){
		pass1.addClass("error");
		pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
		pass1Info.addClass("error");
		return false;
	}
	//it's valid
	else{
		pass1.removeClass("error");
		pass1Info.text("At least 5 characters: letters, numbers and '_'");
		pass1Info.removeClass("error");
		validatePass2();
		return true;
	}
}
function validatePass2(){
	var a = $("#password1");
	var b = $("#password2");
	//are NOT valid
	if( pass1.val() != pass2.val() ){
		pass2.addClass("error");
		pass2Info.text("Passwords doesn't match!");
		pass2Info.addClass("error");
		return false;
	}
	//are valid
	else{
		pass2.removeClass("error");
		pass2Info.text("Confirm password");
		pass2Info.removeClass("error");
		return true;
	}
}
function validateMessage(){
	//it's NOT valid
	if(message.val().length < 10){
		message.addClass("error");
		return false;
	}
	//it's valid
	else{
		message.removeClass("error");
		return true;
	}
}

Như bạn có thể thấy, chúng tôi là & nbsp; thêm và xóa. Các lớperror & nbsp; và & nbsp; thay đổi giá trị văn bản & nbsp; nếu cần & nbsp; hiển thị cho người dùng trường nào sai.adding and removing .error classes and changing text values if needed to show the user what fields are wrong.

Bây giờ chúng tôi đã xác định tất cả các chức năng xác thực, chúng tôi chỉ cần & nbsp; quản lý các sự kiện. Ở đây bạn có những gì chúng ta sẽ làm:manage events. Here you have what we are going to do:

  • Xác thực & nbsp; tên tên & nbsp; in: & nbsp; blur & nbsp; và & nbsp; keyup & nbsp; sự kiện.name field in: blur and keyup events.
  • Xác thực & nbsp; trường email & nbsp; trong: & nbsp; blur & nbsp; sự kiện.email field in: blur event.
  • Xác thực & nbsp; trường mật khẩu & nbsp; trong: & nbsp; blur & nbsp; và & nbsp; keyup & nbsp; sự kiện.password fields in: blur and keyup events.
  • Xác thực & nbsp; trường tin nhắn & nbsp; trong: & nbsp; blur, và & nbsp; keyup & nbsp; sự kiện.message field in: blur, and keyup event.
  • Xác thực & nbsp; tất cả các trường & nbsp; trong: & nbsp; gửi sự kiện biểu mẫu.all fields in: submit form event.

Do đó, mã sẽ là:

//On blur
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
name.keyup(validateName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
	if(validateName() &amp; validateEmail() &amp; validatePass1() &amp; validatePass2() &amp; validateMessage())
		return true
	else
		return false;
});

Như bạn có thể thấy, nó rất dễ kiểm soát bất cứ điều gì chúng tôi muốn bằng cách sử dụng jQuery và một số chức năng. Vì vậy, bây giờ chúng tôi đã thực hiện trang web của Cliend, hãy để di chuyển sang phía máy chủ!let’s move to the server side!

Bước 4: Xác nhận ở phía máy chủ với PHP

Bây giờ chúng tôi đã thực hiện phía khách hàng, hãy để sử dụng sức mạnh của PHP để hoàn thành hướng dẫn của chúng tôi.

Một số bạn có thể & nbsp; nghĩ & nbsp; rằng & nbsp; chúng tôi không cần xác thực phía máy chủ & nbsp; nhưng & nbsp; đó là một lỗi lớn & nbsp; nghĩ về nó. Hãy nhớ rằng & nbsp; chúng tôi có thể tin tưởng & nbsp; trong & nbsp; client & nbsp; side. Trong ví dụ: & nbsp; người dùng có thể vô hiệu hóa javascript & nbsp; trong trình duyệt của họ và & nbsp; gửi cho chúng tôi các giá trị không mong muốn.think that we don’t need the server side validation but it’s a big error thinking about it. Remember that we can’t trust in the client side. In example: users can disable javascript in their browsers and send us undesired values.

Vì vậy, trước hết chúng tôi phải & nbsp; created & nbsp; một tệp .php mới có tên & nbsp; alidation.php & nbsp; sẽ & nbsp; chứa & nbsp;create a new .php file named validation.php that will contains our validation functions written in PHP:

 5;
	}
	function validateMessage($message){
		//if it's NOT valid
		if(strlen($message) < 10)
			return false;
		//if it's valid
		else
			return true;
	}
?>

Như bạn có thể thấy, chúng tôi đã xác định 4 chức năng:

  • Validatename (): Kiểm tra xem tên có ít nhất 4 chữ cái không: checks if name has at least 4 letters
  • ValidateMail (): Kiểm tra xem email có hợp lệ không: checks if email is valid
  • ValidatePasswords (): Kiểm tra xem mật khẩu có bằng nhau không và có ít nhất 5 chữ cái: checks if passwords are equal and have at least 5 letters
  • Validatemessage (): Kiểm tra xem tin nhắn có ít nhất 10 chữ cái không: checks if message has at least 10 letters

Nó gần như đã thực hiện các bạn, chúng tôi chỉ cần thêm một số điều kiện vào & nbsp; index.php của chúng tôi. Nếu bạn nhớ, chúng tôi đã nói rằng chúng tôi sẽ thêm một số điều kiện trong PHP, vì vậy, đã đến lúc làm điều đó:index.php. If you remember, we said that we are going to add some conditionals in the PHP, so it’s time to do that:

  • Chúng tôi sẽ & nbsp; hiển thị #error Division & nbsp; chỉ khi có ít nhất một lỗi.display #error division only if there are at least one error.
  • Chúng tôi sẽ & nbsp; hiển thị #error.valid Division & nbsp; chỉ khi tất cả các trường đều ổn.display #error.valid division only if all fields are OK.

Vì vậy, ở đây bạn có Final & nbsp; index.php & nbsp; bố cục:index.php layout:

@CHARSET "UTF-8";
/******* GENERAL RESET *******/
html, body, div, span, applet, object, iframe, h2, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em,
font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody,
 tfoot, thead, tr, th, td {
border:0pt none;
font-family:inherit;
font-size: 100%;
font-style:inherit;
font-weight:inherit;
margin:0pt;
padding:0pt;
vertical-align:baseline;
}
body{
	background: #fff;
	line-height:14px;
	font-size: 12px;
	font-family: Arial,  Verdana, Helvetica, sans-serif;
	margin:0pt;
	cursor:default;
	overflow: hidden;
}
html,body{
	height:100%;
	text-align: center;
}
.clear{
	clear: both;
	height: 0;
	visibility: hidden;
	display: block;
}
a{
	text-decoration: none;
}
strong{
	font-weight: 700;
}
/******* GENERAL RESET *******/
h2{
	font-weight: 700;
	font-size: 18px;
	line-height: 1.2em;
	border-bottom: 1px dotted #6b9ef1;
	color: #5f95ef;
	margin-bottom: 1em;
}
/******* LOGO *******/
#logo{
	margin-top: 1em;
	display: block;
}
/******* /LOGO  *******/
/******* CONTAINER *******/
#container{
	width: 600px;
	margin: 40px auto;
	text-align: left;
}
/******* /CONTAINER *******/
/******* FORM *******/
#customForm{
	padding: 0 10px 10px;
}
#customForm label{
	display: block;
	color: #797979;
	font-weight: 700;
	line-height: 1.4em;
}
#customForm input{
	width: 220px;
	padding: 6px;
	color: #949494;
	font-family: Arial,  Verdana, Helvetica, sans-serif;
	font-size: 11px;
	border: 1px solid #cecece;
}
#customForm input.error{
	background: #f8dbdb;
	border-color: #e77776;
}
#customForm textarea{
	width: 550px;
	height: 80px;
	padding: 6px;
	color: #adaeae;
	font-family: Arial,  Verdana, Helvetica, sans-serif;
	font-style: italic;
	font-size: 12px;
	border: 1px solid #cecece;
}
#customForm textarea.error{
	background: #f8dbdb;
	border-color: #e77776;
}
#customForm div{
	margin-bottom: 15px;
}
#customForm div span{
	margin-left: 10px;
	color: #b1b1b1;
	font-size: 11px;
	font-style: italic;
}
#customForm div span.error{
	color: #e46c6e;
}
#customForm #send{
	background: #6f9ff1;
	color: #fff;
	font-weight: 700;
	font-style: normal;
	border: 0;
	cursor: pointer;
}
#customForm #send:hover{
	background: #79a7f1;
}
#error{
	margin-bottom: 20px;
	border: 1px solid #efefef;
}
#error ul{
	list-style: square;
	padding: 5px;
	font-size: 11px;
}
#error ul li{
	list-style-position: inside;
	line-height: 1.6em;
}
#error ul li strong{
	color: #e46c6d;
}
#error.valid ul li strong{
	color: #93d72e;
}
/******* /FORM *******/
1

Bạn có thể thấy chúng tôi có & nbsp; bao gồm xác thực.php & nbsp; file & nbsp; trước khi gọi các chức năng xác thực của chúng tôi & nbsp; và thêm một số & nbsp; gọi & nbsp;included the validation.php file before call our validation functions and added some calls to our validation functions to check fields when form is submited.

Chúng tôi đã sử dụng & nbsp; ký hiệu ngắn & nbsp; PHP trong các điều kiện đến & nbsp; giữ cho HTML sạch hơn và dễ đọc hơn.short notation PHP in conditionals to keep the HTML cleaner and easier to read.

Chúng tôi là & nbsp; hiển thị các lỗi / Lời chúc mừng cụm từ cụm từ & nbsp; as & nbsp; cần thiết & nbsp; và bây giờ & nbsp; bạnshowing errors / “congratulations phrase” as needed and now you only need to know what are you doing to do with thisvalidated values 

Hướng dẫn server side validation in php using jquery - xác thực phía máy chủ trong php bằng cách sử dụng jquery

Bước 5: Kiểm tra mẫu xác thực của chúng tôi!

Đó là tất cả các chàng trai, tôi hy vọng bạn thấy nó hữu ích và sử dụng hướng dẫn này để cải thiện thêm một chút trang web của bạn.

Hãy nhớ rằng & nbsp; nếu bạn muốn thử phía máy chủ, & nbsp; bạn cần tắt javascript trong trình duyệt web của mình. Trong Firefox, nó trong các công cụ> Tùy chọn> Nội dung bỏ chọn hộp kiểm Kích hoạt JavaScript JavaScript.if you want to try the server sideyou need to disable the javascript in your web browser. In Firefox it’s in Tools > Options > Content uncheck the “Enable Javascript” checkbox.

Làm thế nào để thực hiện xác thực phía máy chủ trong PHP?

php if (isset ($ _ post ['gửi'])) {$ emp_name = trim ($ _ post ["emp_name"]);$ emp_number = trim ($ _ post ["emp_number"]);$ emp_email = trim ($ _ post ["emp_email"]);if ($ emp_name == "") {$ errorMsg = "error: bạn đã không nhập tên.";$ code = "1";} otherif ($ emp_number == "") {$ errorMsg = "error: vui lòng nhập số.";$ code = "2";} // ...

Chúng ta có thể thực hiện xác thực phía máy chủ bằng JavaScript không?

Nó phụ thuộc vào những gì bạn hiểu bởi "_ làm việc ở phía máy chủ thay vì bên máy khách_".Nếu ở trên, bạn hiểu xác thực di chuyển sang phía máy chủ, thì có, điều đó chắc chắn là có thể.yes, it is definitely possible.