亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Why is client verification important?
Two main verification methods
How to verify the form
Frequently Asked Questions about Form Verification (FAQ)
What is the difference between client verification and server-side verification?
How to implement form validation in PHP?
What are some common verification techniques?
How to display verification error message?
How to verify the checkbox?
How to verify the drop-down list?
How to verify radio buttons?
How to verify the date?
How to verify file upload?
How to prevent SQL injection?
Home Web Front-end JS Tutorial Form Validation on the Client Side

Form Validation on the Client Side

Mar 08, 2025 am 12:12 AM

Form Validation on the Client Side

Client form validation is crucial – it saves time and bandwidth and provides more options to point out where users make mistakes when filling out forms. That being said, this doesn't mean you don't need server-side verification. Users visiting your website may have used an old browser or disabled JavaScript, which will break client-only verification. Client and server-side verification complement each other, so they really should not be used independently.

Why is client verification important?

There are two good reasons to use client authentication:

  1. It is a quick way to verify: if something goes wrong, an alert will be triggered when the form is submitted.

  2. You can safely display only one error at a time and focus on the wrong fields to help ensure that the user fills in all the details you need correctly.

Two main verification methods

The two main methods of client form verification are:

  • Show an error at a time, focus on the problematic fields
  • Show all errors at the same time, server-side verification style

While displaying all errors at the same time is necessary for server-side verification, a better way to verify client is to display one error at a time. This makes it possible to highlight only fields that have been filled incorrectly, which in turn makes it easier for visitors to modify and submit the form successfully. If you present all the errors to the user at the same time, most people will try to remember and correct them at once, rather than trying to resubmit after each correction.

Given these advantages, I will focus only on the verification method that shows one error at a time.

How to verify the form

For example, the following code snippet:

<code><br>
function validateMyForm() { <br>
if (parseInt(document.forms[0].phone.value) ?<br>
 ? ? ? ?!= document.forms[0].phone.value) { <br>
alert('請(qǐng)輸入電話號(hào)碼,僅限數(shù)字'); <br>
return false; <br>
} <br>
 <br>
return true; <br>
} <br>
<br><br></code>

Tel:

What's the problem? Well, if you add another form before this, the code will try to validate the wrong form.

A better way is to include the form name:

<code>function validateMyForm() { <br>
if (parseInt(document.forms.myForm.phone.value) ?<br>
 ? ? ? ?!= document.forms.myForm.phone.value) { <br><br></code>

onsubmit="return validateMyForm();"> This is certainly better, but still not portable enough - if you want to reuse part of this validation on another form, you have to do a lot of text replacement first.

So let's delete the form name:

<code>function validateMyForm(form) { <br>
if (parseInt(form.phone.value) != form.phone.value) { <br><br></code>

This last method uses the object this, which always points to the current object. This makes our code more portable and saves typing time.

How to make the life of visitors easier now? Let's focus on the fields that trigger the error, rather than letting them look it up on their own.

<code>function validateMyForm(form) { <br>
if (parseInt(form.phone.value) != form.phone.value) { <br>
alert('請(qǐng)輸入電話號(hào)碼,僅限數(shù)字'); <br>
form.phone.focus(); <br>
form.phone.select(); <br>
return false; <br>
}</code>

With these changes, the browser will focus on filling in incorrect fields and will even select text for the visitor. This will also happen automatically if scrolling is required.

OK, this is great, but do you think there is a bit too much code for each field? What if we create a simple library of functions that can save a lot of typing and downloading time on the page? Well, next we'll do this - we'll define our basic functions to make the validation code shorter.

<code><br>
function validateMyForm() { <br>
if (parseInt(document.forms[0].phone.value) ?<br>
 ? ? ? ?!= document.forms[0].phone.value) { <br>
alert('請(qǐng)輸入電話號(hào)碼,僅限數(shù)字'); <br>
return false; <br>
} <br>
 <br>
return true; <br>
} <br>
<br><br></code>

This function performs a simple verification of numbers - it checks whether the field contains only numbers and optionally, whether it is within a given range. You will notice that this code passes an error message as a parameter. To use a function like this, we can basically add it to the onsubmit handler as follows:

<code>function validateMyForm() { <br>
if (parseInt(document.forms.myForm.phone.value) ?<br>
 ? ? ? ?!= document.forms.myForm.phone.value) { <br><br></code>

onsubmit="return validateNumber(this.phone,
'Please enter the phone number, only numeric', 5, 10);"> Call it like this, it will check if the phone number is a numeric and is longer than 5 digits and less than 10 digits. Note how to pass the phone object as a parameter? This allows us to focus on it through helper functions instead of just passing the value of the field.

Another way to verify numbers is to require them to be within a given range. To make the function perform such validation, just change the check line to:

<code>function validateMyForm(form) { <br>
if (parseInt(form.phone.value) != form.phone.value) { <br><br></code>

If you want to apply multiple checks to a form, you can embed multiple rules in the onsubmit handler. For example, imagine that in addition to the phone number, we also need to enter our first and last name:

<code>function validateMyForm(form) { <br>
if (parseInt(form.phone.value) != form.phone.value) { <br>
alert('請(qǐng)輸入電話號(hào)碼,僅限數(shù)字'); <br>
form.phone.focus(); <br>
form.phone.select(); <br>
return false; <br>
}</code>

onsubmit="return (
validateNumber(this.phone, 'Please enter the phone
Number, number only', 5, 10) &&
validateString(this.firstName, 'Please enter
Your name', 3, 15) &&
validateString(this.lastName, 'Please enter
Your last name', 3, 15)
);"> The code requires that all validation rules be evaluated as true (using logic AND - &&). A closer look shows that it is very easy to generate such code from the server scripting language...but this is another article.

<code>function validateNumber(field, msg, min, max) { ?<br>
if (!min) { min = 0 } ?<br>
if (!max) { max = 255 } ?<br>
 ?<br>
if ( (parseInt(field.value) != field.value) || ? <br>
 ? ? ? ?field.value.length  max) { ?<br>
alert(msg); ?<br>
field.focus(); ?<br>
field.select(); ?<br>
return false; ?<br>
} ?<br>
 ?<br>
return true; ?<br>
}</code>

As you can see, string validation functions look more or less the same; you can also write other functions and use them in conjunction with these functions.

A common field is required in many forms on the Web, namely the user's email address. I've seen a lot of functions that do this, but usually the easiest and easiest way to verify email addresses is by using regular expressions.

Now we will extend our function so that it can define fields as optional.

<code></code>

To verify the required email, you should call it as:

<code>if ((parseInt(field.value) != field.value) || ? <br>
field.value  max) {</code>

If you want to set it to optional:

<code></code>

JavaScript cannot be used for verification alone, but it can be of great help if you have it. The more compact the code you embed into HTML, the better – it saves download time and search engines will like you!

Frequently Asked Questions about Form Verification (FAQ)

What is the difference between client verification and server-side verification?

Client verification is performed in the user's browser using JavaScript before form data is sent to the server. It provides instant feedback and improves the user experience. However, it can be bypassed by disabling JavaScript or manipulating the code, so it is not completely safe.

On the other hand, server-side verification is performed on the server after submitting the form data. It's safer because users can't bypass it. However, it requires a round trip to the server, which can affect performance and user experience. Therefore, it is recommended to use both client and server-side verification for the best security and user experience.

How to implement form validation in PHP?

PHP provides a variety of form validation functions. For example, you can use the filter_var() function with different filters to validate and clean the input data. Here is a simple example of verifying an email address:

$email = $_POST["email"]; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email format"; } This code checks if the submitted email address is formatted correctly. If not, an error message is displayed.

What are some common verification techniques?

Some common verification techniques include required fields, length limits, pattern matching, and data type checking. Required fields ensure that the user fills in all necessary information. Length limits limit the number of characters that can be entered. Pattern Match Checks if the input matches a specific pattern, such as an email address or phone number. Data type checking ensures that the input is the correct type, such as a number or date.

How to display verification error message?

You can use JavaScript for client verification or server-side verification using PHP to display verification error messages. In JavaScript, you can use the setCustomValidity() method to set up a custom validation message. In PHP, you can store error messages in variables and display them in a form.

How to verify the checkbox?

You can verify the check box by checking whether the check box is selected. In JavaScript, you can use the checked property. In PHP, you can check whether the checkbox value appears in $_POST or $_GET.

How to verify the drop-down list?

You can verify the drop-down list by checking whether the valid option is selected. In JavaScript, you can use the selectedIndex property. In PHP, you can check if the selected value is in an array of valid values.

How to verify radio buttons?

You can verify the radio button by checking whether one of the options is selected. In JavaScript, you can loop through the radio buttons and use the checked property. In PHP, you can check if the radio button value appears in $_POST or $_GET.

How to verify the date?

You can verify the date by checking if the date is formatted correctly and if it is a real date. In JavaScript, you can use the Date object. In PHP, you can use the checkdate() function.

How to verify file upload?

You can verify file uploads by checking file size, file type, and file extension. In JavaScript, you can use the files property. In PHP, you can use the $_FILES array.

How to prevent SQL injection?

You can prevent SQL injection using preprocessed statements or parameterized queries that separate SQL code from data. This prevents the data from being interpreted as code. In PHP, you can use PDO or MySQLi extensions to execute preprocessing statements.

The above is the detailed content of Form Validation on the Client Side. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

var vs let vs const: a quick JS roundup explainer var vs let vs const: a quick JS roundup explainer Jul 02, 2025 am 01:18 AM

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How to traverse the DOM tree (e.g., parentNode, children, nextElementSibling)? How to traverse the DOM tree (e.g., parentNode, children, nextElementSibling)? Jul 02, 2025 am 12:39 AM

DOM traversal is the basis of web page element operation. Common methods include: 1. Use parentNode to obtain the parent node, and can be chained to find it upward; 2. children return a collection of child elements, accessing the first or end child elements through the index; 3. nextElementSibling obtains the next sibling element, and combines previousElementSibling to realize the same-level navigation. Practical applications such as dynamically modifying structures, interactive effects, etc., such as clicking the button to highlight the next brother node. After mastering these methods, complex operations can be achieved through combination.

See all articles