search
HomeWeb Front-endJS TutorialJavaScript form validation encyclopedia

JavaScript form validation encyclopedia

Nov 26, 2016 am 10:11 AM
javascript

<script><br/>function test()<br/>{<br/>if(document.a.b.value.length>50)<br/>{<br/>alert("Cannot exceed 50 characters!");<br/>document.a.b.focus();<br/>return false ;<br/>}<br/>}<br/></script>




2. Can only be Chinese characters

3. Only Can it be in English

<script><br/>function onlyEng()<br/>{<br/>if(!(event.keyCode>=65&&event.keyCode<=90))<br/>event.returnvalue=false;<br/>}<br/></script>

;=96&&event.keyCode//Consider the numeric keys on the small keyboard

event.returnvalue=false;

}





5. Only in English Characters and numbers

('text',clipboardData.getData('text').replace (/[^d]/g,''))">

6. Verify email format




7. Block keywords ( *** and **** are blocked here)

<script><br/>function test() {<br/>if((a.b.value.indexOf ("***") == 0)||(a.b.value.indexOf ( "****") == 0)){<br/>alert(":)");a.b.focus();<p>return false;}}<p></script>




8. Are the passwords entered twice the same?




<script></script>

function check()

{
with(document.all){
if(input1.value!=input2.value )
{
alert("false")
input1.value = "";
input2.value = "";
}
else document.forms[0].submit();
}
}
> ;


That’s enough:)
It’s cool to shield the right click

oncontextmenu="return false"

Add it to the body



2.1 The form item cannot be empty

<script></script>

function CheckForm()
{if (document.form.name.value.length == 0) {

alert("Please enter your name!");

document.form.name.focus();

return false;
}
return true;
}
-->


2.2 Compare whether the values ​​of two form items are the same

<script><br/><!--<br/>function CheckForm( )<br/>if (document.form.PWD.value != document.form.PWD_Again.value) {</script>

alert("The passwords you entered twice are different! Please re-enter.");

document.ADDUser.PWD.focus();

return false;

}
return true;
}
-->


2.3 Form items can only be numbers and "_", used for phone/bank account verification, can be extended to domain name registration, etc.

<script><br/><!--<br/>function isNumber(String)<br/>{</script>

var Letters = "1234567890-"; / /You can add input values ​​by yourself

var i;

var c;

if(String.charAt(0)=='-')
return false;
if(String.charAt(String.length - 1) == ' -' )
return false;
for( i = 0; i {
c = String.charAt( i );
if (Letters.indexOf( c ) return false;
}
return true;
}
function CheckForm()
{
if(! isNumber(document.form.TEL.value)) {
alert("Your phone number is illegal!");
document.form.TEL.focus();
return false;
}
return true;
}
-->



2.4 Form item input value/length limit

<script> <br/><!--<br/>function CheckForm()</script>

{

if (document.form.count.value > 100 || document.form.count.value {

alert("The input value cannot be less than zero Greater than 100!");

document.form.count.focus();
return false;
}
if (document.form.MESSAGE.value.length{
alert("The input text is less than 10!" );
document.form.MESSAGE.focus();
return false;
}
return true;
}
//-->

2.5 Chinese/English/numeric/email address validity judgment

<script><br/><!--<br/>function isEnglish(name) //English value detection<br/>{<br/>if(name.length == 0)<br/>return false;<br/>for(i = 0; i < name.length; i++) {<br/>if(name.charCodeAt(i) > 128)<br/>return false;<br/>}<br/>return true;<br/>}<br/>function isChinese(name) //Chinese value detection<br/>{<br/>if(name.length == 0)<br/>return false;<br/>for(i = 0; i < name.length; i++) {<br/>if(name.charCodeAt(i) > 128 )<br/>return true;<br/>}<br/>return false;<br/>}<br/>function isMail(name) //E-mail value detection<br/>{<br/>if(! isEnglish(name))<br/>return false;<br/>i = name.indexOf(" at ");<br/>j = name dot lastIndexOf(" at ");<br/>if(i == -1)<br/>return false;<br/>if(i != j)<br/>return false;<br/>if(i == name dot length) <br/>return false;<br/>return true;<br/>}<br/>function isNumber(name) //Number detection<br/>{<br/>if(name.length == 0)<br/>return false;<br/>for(i = 0; i < name.length; i++) {<br/>if(name.charAt(i) < "0" || name.charAt(i) > "9")<br/>return false;<br/>}<br/>return true;<br/>}<br/>function CheckForm()<br/>{ <br/>if(! isMail(form.Email.value)) {<br/>alert("Your email is invalid!");<br/>form.Email.focus();<br/>return false;<br/>}<br/>if(! isEnglish(form .name.value)) {<br/>alert("The English name is illegal!");<br/>form.name.focus();<br/>return false;<br/>}<br/>if(! isChinese(form.cnname.value)) {<br/>alert ("The Chinese name is illegal! ");<br/>form.cnname.focus();<br/>return false;<br/>}<br/>if(! isNumber(form.PublicZipCode.value)) {<br/>alert("The postal code is illegal!");<br/>form.PublicZipCode.focus ();<br/>return false;<br/>}<br/>return true;<br/>}<br/>//--><br/></script>

2.6 Limit the characters that cannot be entered in the form item

<script><br/><!-- <br/>function contain(str,charset)//String contains test function<br/>{<br/>var i;<br/>for(i=0;i<charset.length;i++)<br/>if(str.indexOf(charset.charAt(i)) >=0)<br/>return true;<br/>return false;<br/>}<br/>function CheckForm()<br/>{<br/>if ((contain(document.form.NAME.value, "%()><")) || ( contain(document.form.MESSAGE.value, "%</script>

()>{
alert("Illegal characters entered");
document.form.NAME.focus();
return false;
}
return true;
}
//-->

1. Check whether a string consists entirely of numbers
------------- ---------------------------


& lt; script & gt; & lt;!-
Function Checknum (STR) {Return Str.match ( +​
---------------------------------------
if (/[^x00-xff]/ g.test(s)) alert("Contains Chinese characters");      
else alert("All characters"); --------------------------
if (escape(str).indexOf("%u")!=-1) alert("Contains Chinese characters ");
else alert("All characters");

4. Email format verification
----------------------------- -----------
//Function name: chkemail
//Function introduction: Check whether it is an Email Address
//Parameter description: The string to be checked
//Return value: 0: not 1 :Yes
function chkemail(a)

{ var i=a.length;

var temp = a.indexOf('@');
var tempd = a.indexOf('.');
if (temp > 1 ) {
if ((i-temp) > 3){
if ((i-tempd)>0){
return 1;
}

}
}
return 0;
}

5. Number Format verification
---------------------------------------------

//Function name: fucCheckNUM

//Function introduction: Check whether it is a number
//Parameter description: The number to be checked
//Return value: 1 means it is a number, 0 means it is not a number
function fucCheckNUM(NUM)

{

var i,j,strTemp;
strTemp="0123456789";
if (NUM.length== 0)
return 0
for (i=0;i{
j=strTemp.indexOf(NUM.charAt(i) );
if (j==-1)
{
//Indicates that the character is not a number
return 0;
}
}
//Indicates that it is a number
return 1;
}

6. Phone number format verification
---------------------------------------------
// Function name: fucCheckTEL
//Function introduction: Check whether it is a phone number
//Parameter description: The string to be checked
//Return value: 1 is legal, 0 is illegal
function fucCheckTEL(TEL)
{
var i,j,strTemp;
strTemp="0123456789-()# ";
for (i=0;i{
j=strTemp.indexOf(TEL.charAt(i));
if (j==-1)
{
//Indicates that the characters are illegal
return 0;
}
}
//Indicates that it is legal www.2cto.com
return 1;
}

7. Determine whether the input is a Chinese function
---------------------------------------------
function ischinese(s) {
var ret=true;
for(var i=0;iret=ret && (s.charCodeAt(i)>=10000);
return ret;
}

8 . Comprehensive function to judge the legality of user input
------------------------------------------------ -
<script><br/>//Start by limiting the number of digits to be entered<br/>//m is user input, n is the number of digits to be limited<br/>function issmall(m,n)<br/>{<br/>if ((m<n) && (m>0))<br/>{<br/>return(false);<br/>}<br/>else<br/>{return(true);}<br/>}</script>

9. Determine whether the passwords are entered consistently
------------ --------------------------
function issame(str1,str2)
{
if (str1==str2)
{return(true );}
else
{return(false);}
}

10. Determine whether the user name is a numeric letter underline
--------------------- ------------------
function notchinese(str){
var reg=/[^A-Za-z0-9_]/g
if (reg.test(str )){
return (false);
}else{
return(true); }
}

11. General verification function for form text field
-------------------------- --------------------------
Function: Detect all input text that must be non-empty, such as name, account number, email address, etc.
This check is now only for the text field. If you want to target other field objects in the form, you can change the judgment conditions.

How to use: Add title text to the text field to be detected. The text is the prompt information. You want to prompt the Chinese name of the field to the user. For example, if you want to detect

username
html as follows , of course, it is best to use a visual tool such as Dreamweaver to edit the domain.
If you want to detect numeric type data, then unify the domain ID to sz.
It is troublesome for JavaScript to determine the date type, so there is no program for date type verification. Experts can add.

The program is relatively crude, I just provide an idea. Throw some bricks to attract good news! :)
Oh, by the way, function calling method:

function dovalidate()
{
fm=document.forms[0] //Only detect one form, if there are multiple, you can change the judgment condition
for (i=0;i{
//Detection and judgment conditions, which can be modified according to different types
if(fm[i].tagName.toUpperCase()=="INPUT" &&fm[i]. type.toUpperCase()=="TEXT" && (fm[i].title!=""))

if(fm[i].value="/blog/="")//
{
str_warn1= fm[i].title+"Can't be empty!";
alert(str_warn1);
fm[i].focus();
return false; }
if(fm[i].id.toUpperCase()== "SZ")//Digital verification
                                                                                                                                                                         fm[i] .focus();
                                                                    return false;

<script><br/><! --<br/>function CheckForm()<br/>{<br/>if (document.form.name.value.length == 0) {<br/>alert("Please enter your name!");<br/>document.form.name.focus();<br/> return false;<br/>}</script>

return true;

}
-->


2.2 Compare whether the values ​​of two form items are the same

<script><br/><!--<br/>function CheckForm()<br/>if (document.form.PWD.value != document.form.PWD_Again.value) {<br/>alert("The passwords you entered twice are different! Please re-enter.");<br/>document.ADDUser.PWD.focus();<br/>return false;<br/>}<br/>return true;<br/>}<br/>--><br/></script>

2.3 Form items can only be numbers and "_", used for phone/bank account verification, can be extended to domain name registration, etc.

<script><br/><!--<br/>function isNumber(String)<br/>{<br/>var Letters = "1234567890-"; / /You can add input values ​​by yourself<br/>var i;<br/>var c;<br/>if(String.charAt(0)=='-')<br/>return false;<br/>if(String.charAt(String.length - 1) == ' -' )<br/>return false;<br/>for( i = 0; i < String.length; i ++ )<br/>{<br/>c = String.charAt( i );<br/>if (Letters.indexOf( c ) < 0) <br/>return false;<br/>}<br/>return true;<br/>}<br/>function CheckForm()<br/>{<br/>if(! isNumber(document.form.TEL.value)) {<br/>alert("Your phone number is illegal!");<br/> document.form.TEL.focus();<br/>return false;<br/>}<br/>return true;<br/>}<br/>--><br/></script>


2.4 Form item input value/length limit

<script> <br/><!--<br/>function CheckForm()<br/>{<br/>if (document.form.count.value > 100 || document.form.count.value < 1)<br/>{<br/>alert("The input value cannot be less than zero Greater than 100!");<br/>document.form.count.focus();<br/>return false;<br/>}<br/>if (document.form.MESSAGE.value.length<10)<br/>{<br/>alert("The input text is less than 10!" );<br/>document.form.MESSAGE.focus();<br/>return false;<br/>}<br/>return true;<br/>}<br/>//--><br/></script>

2.5 Chinese/English/numeric/email address is legal Sex judgment

<script><br/><!--</script>

function isEnglish(name) //English value detection
{
if(name.length == 0)
return false;
for(i = 0; i if(name.charCodeAt(i) > 128)
return false;
}
return true;
}

function isChinese(name) //Chinese value detection
{
if (name.length == 0)
return false;
for(i = 0; i if(name.charCodeAt(i) > 128)
return true;
}
return false;
}

function isMail(name) //E-mail value detection
{
if(! isEnglish(name))
return false;
i = name.indexOf(" at ");
j = name dot lastIndexOf(" at ");
if(i == -1)
return false;
if(i != j)
return false;
if(i == name dot length)
return false;
return true;
}

function isNumber(name) //Numerical detection
{
if(name.length == 0)
return false;
for(i = 0; i if(name .charAt(i) "9")
return false;
}
return true;
}

function CheckForm()
{
if(! isMail( form.Email.value)) {
alert("Your email is illegal! ");
form.Email.focus();
return false;
}
if(! isEnglish(form.name.value)) {
alert("The English name is illegal!");
form.name.focus ();
return false;
}
if(! isChinese(form.cnname.value)) {
alert("The Chinese name is illegal!");
form.cnname.focus();
return false;
}
if(! isNumber(form.PublicZipCode.value)) {
alert("The postal code is illegal!");
form.PublicZipCode.focus();
return false;
}
return true;
}
// -->

2.6 Limit the characters that cannot be entered in the form item

<script><br/><!--</script>

function contain(str,charset)//The string contains the test function
{
var i;
for(i=0;iif(str.indexOf(charset.charAt(i))>=0)
return true;
return false;
}

function CheckForm()
{
if ((contain(document.form.NAME.value, "%()>

() >{
alert("Illegal characters entered");
document.form.NAME.focus();
return false;
}
return true;
}
//--> ;


Statement
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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment