"/> ">
search
HomeWeb Front-endJS TutorialHow to fully validate a form using regular expressions and javascript

Please save the following javascript code into a single js file when using it.
1. Form requirements

<form name="formname" onSubmit="return validateForm(this)"></form>

will verify all the following types of fields in the form in sequence. All verifications will remove leading and suffix spaces. Please note that they are case-sensitive.
2. Empty value verification
Adding the emptyInfo attribute to any field in the form will verify whether the field is empty (can be used at the same time as the general verification method of maximum length verification).
Without this attribute, it is considered that this field allows null values.
For example:
3. Maximum length verification (can be used together with null value verification and general verification methods):

or,3. General verification method (no verification of null values):
For example:
4. Standard verification (not used simultaneously with other verification methods):
All implemented through , and the name attribute is not required to avoid submission to the server.
4.1. Valid date verification:

<input type="text" name="yearfieldName" value="2004">注:这里也可以是<select name="yearfieldName"></select>,以下同
<input type="text" name="monthfieldName" value="02">
<input type="text" name="dayfieldName" value="03">
<input type="hidden" validatorType="DateGroup" year="yearfieldName" month="monthfieldName" day="dayfieldName" errorInfo="不正确的日期!">

yearfieldName, monthfieldName, and dayfieldName are year, month, and day fields respectively. Month and day can be in two-digit (MM) or one-digit format (M).
Each field is not tested separately here. (If you want to verify, please use the previous general verification method in the three fields of year, month and day respectively), only check whether the maximum value of the date is legal;
4.2, date format verification (please note that this verification does not verify whether the date is valid , I haven’t found a way to get the year, month and day data from the format yet^_^):

<input type="text" name="datefieldName" value="2003-01-03 21:31:00">
<input type="hidden" validatorType="Date" fieldName="datefieldName"; format="yyyy-MM-dd HH:mm:ss" errorInfo="不正确的日期!">

The format only supports y, M, d, H, m, s (other characters are considered non-time characters)
4.3. List verification:
Check whether at least one record is selected in the list (checkbox, redio, select) (mainly used for multiple selections for select)

<input type="checkbox" name="checkbox1">
<input type="hidden" validatorType="Checkbox" fieldName="checkbox1" errorInfo="请至少选中一条记录!">

The validatorType can be Checkbox, R, Select;
For a select form, if you are required to select a record that cannot be the first record, please use the following method:

<select name="select1" emptyInfo="请选择一个选项!">
<option value="">==请选择==</option>
<option value="1">1</option>
<select>

4.4. Email verification:

<input type="text" name="email">
<input type="hidden" fieldName="email" validatorType="Email" separator="," errorInfo="不正确的Email!">

where separator is optional, indicating the separator when entering multiple emails (without this The option can only be one address)
4.5. Add other javascript operations:

<script type="text/javascript">
function functionname(){
自定义方法
}
</script>
表单中加入<input type="hidden" validatorType="javascript" functionName="functionname">(此时emptyInfo等属性无效)
时将调用function属性中指定的javascript方法(要求方法返回true或false,返回false将不再验证表单,也不提交表单)。
5、在表单通过验证提交前disable一个按钮(也可将其它域disable,不能与其它验证同在一个域),不要求按钮是表单中的最后一个
<input type="button" name="提交" validatorType="disable">
6、不验证表单
<input type="hidden" name="validate" value="0" functionName="functionname">
当validator域值为0时不对表单进行验证,直接提交表单或执行指定function并返回true后提交表单
functionName为可选
-->
<script type="text/javascript">
function getStringLength(str){
var endvalue=0;
var sourcestr=new String(str);
var tempstr;
for (var strposition = 0; strposition < sourcestr.length; strposition ++) {
tempstr=sourcestr.charAt(strposition);
if (tempstr.charCodeAt(0)>255 || tempstr.charCodeAt(0)<0) {
endvalue=endvalue+2;
} else {
endvalue=endvalue+1;
}
}
return(endvalue);
}
function trim(str){
if(str==null) return "";
if(str.length==0) return "";
var i=0,j=str.length-1,c;
for(;i<str.length;i++){
c=str.charAt(i);
if(c!=&#39; &#39;) break;
}
for(;j>-1;j--){
c=str.charAt(j);
if(c!=&#39; &#39;) break;
}
if(i>j) return "";
return str.substring(i,j+1);
}
function validateDate(date,format,alt){
var time=trim(date.value);
if(time=="") return;
var reg=format;
var reg=reg.replace(/yyyy/,"[0-9]{4}");
var reg=reg.replace(/yy/,"[0-9]{2}");
var reg=reg.replace(/MM/,"((0[1-9])|1[0-2])");
var reg=reg.replace(/M/,"(([1-9])|1[0-2])");
var reg=reg.replace(/dd/,"((0[1-9])|([1-2][0-9])|30|31)");
var reg=reg.replace(/d/,"([1-9]|[1-2][0-9]|30|31))");
var reg=reg.replace(/HH/,"(([0-1][0-9])|20|21|22|23)");
var reg=reg.replace(/H/,"([0-9]|1[0-9]|20|21|22|23)");
var reg=reg.replace(/mm/,"([0-5][0-9])");
var reg=reg.replace(/m/,"([0-9]|([1-5][0-9]))");
var reg=reg.replace(/ss/,"([0-5][0-9])");
var reg=reg.replace(/s/,"([0-9]|([1-5][0-9]))");
reg=new RegExp("^"+reg+"$");
if(reg.test(time)==false){//验证格式是否合法
alert(alt);
date.focus();
return false;
}
return true;
}
function validateDateGroup(year,month,day,alt){
var array=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var y=parseInt(year.value);
var m=parseInt(month.value);
var d=parseInt(day.value);
var maxday=array[m-1];
if(m==2){
if((y%4==0&&y%100!=0)||y%400==0){
maxday=29;
}
}
if(d>maxday){
alert(alt);
return false;
}
return true;
}
function validateCheckbox(obj,alt){
var rs=false;
if(obj!=null){
if(obj.length==null){
return obj.checked;
}
for(i=0;i<obj.length;i++){
if(obj[i].checked==true){
return true;
}
}
}
alert(alt);
return rs;
}
function validateRadio(obj,alt){
var rs=false;
if(obj!=null){
if(obj.length==null){
return obj.checked;
}
for(i=0;i<obj.length;i++){
if(obj[i].checked==true){
return true;
}
}
}
alert(alt);
return rs;
}
function validateSelect(obj,alt){
var rs=false;
if(obj!=null){
for(i=0;i<obj.options.length;i++){
if(obj.options[i].selected==true){
return true;
}
}
}
alert(alt);
return rs;
}
function validateEmail(email,alt,separator){
var mail=trim(email.value);
if(mail=="") return;
var em;
var myReg = /^[_a-z0-9]+@([_a-z0-9]+\.)+[a-z0-9]{2,3}$/;
if(separator==null){
if(myReg.test(email.value)==false){
alert(alt);
email.focus();
return false;
}
}
else{
em=email.value.split(separator);
for(i=0;i<em.length;i++){
em[i]=em[i].trim();
if(em[i].length>0&&myReg.test(em[i])==false){
alert(alt);
email.focus();
return false;
}
}
}
return true;
}
function validateForm(theForm){// 若验证通过则返回true
var disableList=new Array();
var field = theForm.elements; // 将表单中的所有元素放入数组
for(var i = 0; i < field.length; i++){
var vali=theForm.validate;
if(vali!=null){
if(vali.value=="0"){
var fun=vali.functionName;
if(fun!=null){
return eval(fun+"()");
}
else{
return true;
}
}
}
var empty=false;
var value=trim(field[i].value);
if(value.length==0){//是否空值
empty=true;
}
var emptyInfo=field[i].emptyInfo;//空值验证
if(emptyInfo!=null&&empty==true){
alert(emptyInfo);
field[i].focus();
return false;
}
var lengthInfo=field[i].lengthInfo;//最大长度验证
if(lengthInfo!=null&&getStringLength(value)>field[i].maxLength){
alert(lengthInfo);
field[i].focus();
return false;
}
var validatorType=field[i].validatorType;
if(validatorType!=null){//其它javascript
var rs=true;
if(validatorType=="javascript"){
eval("rs="+field[i].functionName+"()");
if(rs==false){
return false;
}
else{
continue;
}
}
else if(validatorType=="disable"){//提交表单前disable的按钮
disableList.length++;
disableList[disableList.length-1]=field[i];
continue;
}
else if(validatorType=="Date"){
rs=validateDate(theForm.elements(field[i].fieldName),field[i].format,field[i].errorInfo);
}
else if(validatorType=="DateGroup"){
rs=validateDateGroup(theForm.elements(field[i].year),theForm.elements(field[i].month),theForm.elements(field[i].day),field[i].errorInfo);
}
else if(validatorType=="Checkbox"){
rs=validateCheckbox(theForm.elements(field[i].fieldName),field[i].errorInfo);
}
else if(validatorType=="Radio"){
rs=validateRadio(theForm.elements(field[i].fieldName),field[i].errorInfo);
}
else if(validatorType=="Select"){
rs=validateSelect(theForm.elements(field[i].fieldName),field[i].errorInfo);
}
else if(validatorType=="Email"){
rs=validateEmail(theForm.elements(field[i].fieldName),field[i].errorInfo);
}
else{
alert("验证类型不被支持, fieldName: "+field[i].name);
return false;
}
if(rs==false){
return false;
}
}
else{//一般验证
if(empty==false){
var v = field[i].validator; // 获取其validator属性
if(!v) continue; // 如果该属性不存在,忽略当前元素
var reg=new RegExp(v);
if(reg.test(field[i].value)==false){
alert(field[i].errorInfo);
field[i].focus();
return false;
}
}
}
}
for(i=0;i<disableList.length;i++){
disableList[i].disabled=true;
}
return true;
}
</script>


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
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

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 Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools