"/> ">

Home  >  Article  >  Web Front-end  >  How to fully validate a form using regular expressions and javascript

How to fully validate a form using regular expressions and javascript

伊谢尔伦
伊谢尔伦Original
2016-11-22 14:21:53929browse

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: 89938abed011362bcc4fc3f33799f6a0
3. Maximum length verification (can be used together with null value verification and general verification methods):
f65bdacd7923d5f608039389fa1d1dcd
or,d9d7c0bd03adcc21079d384bb942cc3e
4. Standard verification (not used simultaneously with other verification methods):
All implemented through 10a0c4c6fe334f1dd2642c4aa224944a, 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