Introduction to JavaScript form validation function
I am learning JavaScript recently, so I thought of using js to implement form verification. Through this article, I will share with you the steps to use javascript to implement the form verification function. Friends who need it can refer to it
Text box verification
The following are the verification steps for the text box.
1. Get the value of the text box to be verified,
2. Set judgment conditions on the value, using if statements or switch statements.
3. If the conditions are met, the verification passes and the return value is true.
4. If the condition is not met, the return value is false, and the text is replaced to output the verification prompt information.
5. The form obtains the return values of multiple verifications, performs logical operations, and passes the parameters to the onsubmit event of the form.
6. Call the verification function in the input. I use the onblur event to trigger the verification function.
Drop-down box verification
The verification of the drop-down box is slightly different than that of the text box. The return value of the option in the drop-down box is value , the user's choice is obtained from the name value in the select, so the value in the select is obtained through the id in the verification function of the drop-down box, and different judgments are made based on whether the value is empty or other illegal values. The rest of the steps are the same as for the text box.
The form verification style is as follows:
#Problems encountered
- There was a problem when validating the form But the form can still be submitted?
- Reason: The onsubmit event has a default parameter as a submission action. The default value of this parameter is true. As mentioned earlier, if the conditions are met, it will return true, otherwise it will return false. Each time A Boolean return value must be set in the verification of the items. If all verifications pass, the form can be submitted normally. As long as one item does not meet the conditions, the form cannot be submitted and needs to be re-entered. Therefore, each item needs to be verified. The return value of the function performs a logical operation. If all are true, the final value returned to onsubmit is true, otherwise it is false. If the parameter of onsubmit is false, it cannot be submitted, so it is implemented to prevent submission when the form verification fails.
- I entered the wrong content at the beginning, but after modifying it to the correct content, the prompt is still the same as before?
- Reason: When the return value is true, the text content of the output prompt message is set to empty, that is, document.getElementById("What").innerHTML="";
- Both onchange and onblur events can be used to trigger verification, and both will implement verification after losing focus. However, when onblur triggers verification, the user may be prompted for input due to intermittent input. The content does not meet the requirements.
- The js code snippet for form verification cannot be loaded after the page is loaded.
Code block
The following is the program source code:<script> function validateUsername(){ var input = document.myform.userName.value; if(input == “”||input == null) { document.myform.userName.focus(); document.getElementById(“uname”).innerHTML=”用户名不能为空!”; return false; } else if(input.length>5 || input.length<2){ document.getElementById(“uname”).innerHTML= “用户名在2~5位”; document.myform.userName.focus(); return false; } else{ document.getElementById(“uname”).innerHTML=”“; return true; } } function validatePassword(){ var password = document.myform.password.value; if(password == “”||password == null) { document.getElementById(“upss”).innerHTML = “密码不能为空!”; document.myform.password.focus(); return false; } else if(password.length>12 || password.length<6){ document.getElementById(“upss”).innerHTML= “密码在6~12位”; document.myform.password.focus(); return false; } else{ document.getElementById(“upss”).innerHTML= “”; return true; } } function validatePasswordAgain(){ var psw = document.myform.psw.value; var password = document.myform.password.value; if(psw!=password){ document.getElementById(“upssa”).innerHTML=”两次密码输入不同”; return false; }else{ document.getElementById(“upssa”).innerHTML = “”; return true; } } function validateGroup(){ var select = document.getElementById(“select”); if(select.value == “NONE”){ document.getElementById(“groupID”).innerHTML=”请选择分组!”; return false; }else { document.getElementById(“groupID”).innerHTML=”“; return true; } } function validateForm(){ var flag = validateUsername()&&validatePassword()&&validatePasswordAgain()&&validateGroup(); if(flag){ return true; }else return false; }
<p class="warp"> <h1 id="新用户注册">新用户注册</h1> <form action="/myproject/admin/addUser" name="myform" onsubmit="return validateForm()"> <p class="form-warp"> <ul> <li>用户名称:<input class="input" type="text" name="userName" placeholder="请输入..." onblur="validateUsername()"/></li> <li>密 码:<input class="input" type="password" name="password" id="password" placeholder="请输入..." onblur="validatePassword()"/></li> <li>确认密码:<input class="input" type="password" name="psw" id="psw" placeholder="请输入..." onblur="validatePasswordAgain()"/></li> <li>真实姓名:<input class="input" type="text" name="realName" placeholder="请输入..."/></li> <li>分 组:<select name="group.id" id="select" onblur="validateGroup()"> <option value="NONE">请选择...</option> <#list groups as group> <option value="${group.id}">${group.name}</option> </#list> </select> </li> <li><input type="submit" value="提交" id="button"/></li> </ul> <ul class="validate"> <li id="uname"></li> <li id="upss"></li> <li id="upssa"></li> <li id="groupID"></li> </ul> </p> </form> </p> “`
The above is the detailed content of Introduction to JavaScript form validation function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin
