


How 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):
< input type="text" name="fieldNamename" maxlength="20" lengthInfo="The maximum length cannot exceed 20!">
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!=' ') break; } for(;j>-1;j--){ c=str.charAt(j); if(c!=' ') 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>

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

AI Hentai Generator
Generate AI Hentai for free.

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



PHP regular expression verification: Number format detection When writing PHP programs, it is often necessary to verify the data entered by the user. One of the common verifications is to check whether the data conforms to the specified number format. In PHP, you can use regular expressions to achieve this kind of validation. This article will introduce how to use PHP regular expressions to verify number formats and provide specific code examples. First, let’s look at common number format validation requirements: Integers: only contain numbers 0-9, can start with a plus or minus sign, and do not contain decimal points. floating point

To validate email addresses in Golang using regular expressions, follow these steps: Use regexp.MustCompile to create a regular expression pattern that matches valid email address formats. Use the MatchString function to check whether a string matches a pattern. This pattern covers most valid email address formats, including: Local usernames can contain letters, numbers, and special characters: !.#$%&'*+/=?^_{|}~-`Domain names must contain at least One letter, followed by letters, numbers, or hyphens. The top-level domain (TLD) cannot be longer than 63 characters.

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

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

PHP Regular Expressions: Exact Matching and Exclusion Fuzzy inclusion regular expressions are a powerful text matching tool that can help programmers perform efficient search, replacement and filtering when processing text. In PHP, regular expressions are also widely used in string processing and data matching. This article will focus on how to perform exact matching and exclude fuzzy inclusion operations in PHP, and will illustrate it with specific code examples. Exact match Exact match means matching only strings that meet the exact condition, not any variations or extra words.

The method of using regular expressions to verify passwords in Go is as follows: Define a regular expression pattern that meets the minimum password requirements: at least 8 characters, including lowercase letters, uppercase letters, numbers, and special characters. Compile regular expression patterns using the MustCompile function from the regexp package. Use the MatchString method to test whether the input string matches a regular expression pattern.

PHP is a widely used programming language, especially popular in the field of web development. In the process of web development, we often encounter the need to filter and verify text input by users, among which character filtering is a very important operation. This article will introduce how to use regular expressions in PHP to implement Chinese character filtering, and give specific code examples. First of all, we need to clarify that the Unicode range of Chinese characters is from u4e00 to u9fa5, that is, all Chinese characters are in this range.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
