Javascript OOP表单验证程序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript OOP表单验证程序相关的知识,希望对你有一定的参考价值。
Just thought id put up a version of my form validation class. It will be expanded in the future but I thought Id let everyone have a look.# Update 0.1 #
* Create Error List Function
* Validate Email Address Function
* Validate Length of field
/* Author: Alvin Crespo Date: 2/18/2010 Description: javascript Field Validation Class */ function ValidateFields(pFormID){ var aForm = document.getElementById(pFormID); this.errArray = new Array();//error tracker } /* * ValidateEmail * * @id - id element of the email addres * * Validates a given email address * * returns nothing * */ ValidateFields.prototype.ValidateEmail = function(id){ var emailVal = document.getElementById(id).value; //check length of email if(this.ValidateLength(emailVal)){ this.errArray.push("You must provide an email."); return; } else{ //do nothing } //check validity of the email using regex var regexpr = /^([0-9a-zA-Z]([-.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+[a-zA-Z]{2,9})$/; var emailResult = regexpr.test(emailVal); if(!emailResult){ this.errArray.push("Your email is invalid."); return; } else{ //do nothing } } /* * ValidateLength() * * @aFieldEle - element of a field * * Validates the length of a given element * * returns true or false * */ ValidateFields.prototype.ValidateLength = function(aFieldEle){ //check that the value is greater than 0 if(aFieldEle.length <= 0){ return true; //less than 0 } else{ return false; //greater than 0 } } /* * CreateErrorList() * * @formstatid - id of a form * * Places the errors after the form * * returns nothing */ ValidateFields.prototype.CreateErrorList = function(formstatid){ var statList = document.getElementById(formstatid).getElementsByTagName('ul')[0]; for(var i = 1; i<=this.errArray.length; i++){ var aLI = document.createElement('li'); var aLIText = document.createTextNode(this.errArray[i-1]); aLI.appendChild(aLIText); statList.appendChild(aLI); } }
以上是关于Javascript OOP表单验证程序的主要内容,如果未能解决你的问题,请参考以下文章
原生JavaScript判断是否为邮箱危险字符验证长度验证网址验证小数整数浮点数等常用的验证