JavaScript DHTML/Form Control/Validation — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:21, 26 мая 2010
Содержание
- 1 A CSS is used to highlight the fields which failed to validate
- 2 A simple form with two passwords that must have the same value
- 3 Can be empty
- 4 ComboBox(list box): Must be selected one
- 5 Creating Reusable Validation Code
- 6 Credit Card Validation
- 7 Form validation: Not Empty, Valid Radio, is Number, string length, EMail Address
- 8 Form validator library
- 9 InputBox: value must be between 10 and 90
- 10 Javascript validation framework
- 11 Money Format
- 12 Must be at least 3 characters and not more than 8
- 13 Must be a valid email address
- 14 Need to select a file
- 15 Not stop when the first failed validation is encountered
- 16 Only characters are allowed
- 17 Password field validator
- 18 Phone Number Validation
- 19 Shows the usage of callback functions for checking a field
- 20 TextField input length validator
- 21 TextField validator: email, IP address and URL
- 22 Validate an field with a maximum number of characters
- 23 Validate an input field with minimum and maximum values
- 24 Validate a number
- 25 Validate email address
- 26 Validating User Input
A CSS is used to highlight the fields which failed to validate
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>Neues Dokument</title>
</head>
<body>
</body>
</html><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Exmaple 3</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 3</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateCompleteForm(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
A simple form with two passwords that must have the same value
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 5</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(images/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
</head>
<body style="margin: 10px 10px 10px 10px">
<h1>Example 5</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" required="1" regexp="/^\w*$/" realname="Username" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td class="mandatory">Password 1:</td>
<td><input type="password" name="password1" id="password1" required="1" minlength="3" maxlength="8"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Password 2:</td>
<td><input type="password" name="password2" id="password2" required="1" equals="password1" err="Password two must be the same as password 1"></td>
<td class="comment">//--- must be equal than Password 1</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Can be empty
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 1</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.name.realname = "Username";
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 1</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
ComboBox(list box): Must be selected one
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 1</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.name.realname = "Username";
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 1</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Creating Reusable Validation Code
<html>
<head>
<title>Integer Validation</title>
<script language="JavaScript">
<!--
function isInt(textObj) {
var newValue = textObj.value;
var newLength = newValue.length;
for(var i = 0; i != newLength; i++) {
aChar = newValue.substring(i,i+1);
if(aChar < "0" || aChar > "9") {
return false;
}
}
return true;
}
// -->
</script>
</head>
<body>
<h1>Integer Validation</h1>
<form name="form1">
<input type="text" size=16 maxlength=16 name="data">
<input type="button" name="CheckButton" value="Validate" onClick="document.form1.result.value = "" + isInt(document.form1.data)">
<br>
Result <input type="text" size=16 maxlength=16 name="result">
</form>
</body>
</html>
Credit Card Validation
/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke
ISBN: 067231763X
Publisher Sams CopyRight 2000
*/
<html>
<head>
<title>Credit Card Validation</title>
<script language="JavaScript">
<!--begin script
function isCreditCard(textObj) {
/*
* This function validates a credit card entry.
* If the checksum is ok, the function returns true.
*/
var ccNum;
var odd = 1;
var even = 2;
var calcCard = 0;
var calcs = 0;
var ccNum2 = "";
var aChar = "";
var cc;
var r;
ccNum = textObj.value;
for(var i = 0; i != ccNum.length; i++) {
aChar = ccNum.substring(i,i+1);
if(aChar == "-") {
continue;
}
ccNum2 = ccNum2 + aChar;
}
cc = parseInt(ccNum2);
if(cc == 0) {
return false;
}
r = ccNum.length / 2;
if(ccNum.length - (parseInt(r)*2) == 0) {
odd = 2;
even = 1;
}
for(var x = ccNum.length - 1; x > 0; x--) {
r = x / 2;
if(r < 1) {
r++;
}
if(x - (parseInt(r) * 2) != 0) {
calcs = (parseInt(ccNum.charAt(x - 1))) * odd;
}
else {
calcs = (parseInt(ccNum.charAt(x - 1))) * even;
}
if(calcs >= 10) {
calcs = calcs - 10 + 1;
}
calcCard = calcCard + calcs;
}
calcs = 10 - (calcCard % 10);
if(calcs == 10) {
calcs = 0;
}
if(calcs == (parseInt(ccNum.charAt(ccNum.length - 1)))) {
return true;
}
else {
return false;
}
}
// end script-->
</script>
</head>
<BODY>
<h1>Credit Card Validation</h1>
<form name="form1">
<input type="text"
size=16
maxlength=16
name="data">
<input type="button"
name="CheckButton"
value="Validate"
onClick="document.form1.result.value = "" +
isCreditCard(document.form1.data)">
<br>
Result <input type="text"
size=16
maxlength=16
name="result">
</form>
</body>
</html>
Form validation: Not Empty, Valid Radio, is Number, string length, EMail Address
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Example File From "JavaScript and DHTML Cookbook"
Published by O"Reilly & Associates
Copyright 2003 Danny Goodman
-->
<html>
<head>
<title>Recipes 8.2, 8.3, and 8.4</title>
<style rel="stylesheet" id="mainStyle" type="text/css">
html {background-color:#cccccc}
body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; font-size:12px;
margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}
h1 {text-align:right; font-size:1.5em; font-weight:bold}
h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline}
.buttons {margin-top:10px}
</style>
<script type="text/javascript">
// validates that the field value string has one or more characters in it
function isNotEmpty(elem) {
var str = elem.value;
var re = /.+/;
if(!str.match(re)) {
alert("Please fill in the required field.");
setTimeout("focusElement("" + elem.form.name + "", "" + elem.name + "")", 0);
return false;
} else {
return true;
}
}
//validates that the entry is a positive or negative number
function isNumber(elem) {
var str = elem.value;
var re = /^[-]?\d*\.?\d*$/;
str = str.toString();
if (!str.match(re)) {
alert("Enter only numbers into the field.");
setTimeout("focusElement("" + elem.form.name + "", "" + elem.name + "")", 0);
return false;
}
return true;
}
// validates that the entry is 16 characters long
function isLen16(elem) {
var str = elem.value;
var re = /\b.{16}\b/;
if (!str.match(re)) {
alert("Entry does not contain the required 16 characters.");
setTimeout("focusElement("" + elem.form.name + "", "" + elem.name + "")", 0);
return false;
} else {
return true;
}
}
// validates that the entry is formatted as an e-mail address
function isEMailAddr(elem) {
var str = elem.value;
var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!str.match(re)) {
alert("Verify the e-mail address format.");
setTimeout("focusElement("" + elem.form.name + "", "" + elem.name + "")", 0);
return false;
} else {
return true;
}
}
// validate that the user made a selection other than default
function isChosen(select) {
if (select.selectedIndex == 0) {
alert("Please make a choice from the list.");
return false;
} else {
return true;
}
}
// validate that the user has checked one of the radio buttons
function isValidRadio(radio) {
var valid = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
return true;
}
}
alert("Make a choice from the radio buttons.");
return false;
}
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
elem.focus();
elem.select();
}
// batch validation router
function validateForm(form) {
if (isNotEmpty(form.name1)) {
if (isNotEmpty(form.name2)) {
if (isNotEmpty(form.eMail)) {
if (isEMailAddr(form.eMail)) {
if (isChosen(form.continent)) {
if (isValidRadio(form.accept)) {
return true;
}
}
}
}
}
}
return false;
}
</script>
</head>
<body>
<h1>Form Validations</h1>
<hr />
<form method="GET" action="cgi-bin/register.pl" name="sampleForm"
onsubmit="return validateForm(this)">
First Name:
<input type="text" size="30" name="name1" id="name1" onchange="isNotEmpty(this)" />
<br>
Last Name:
<input type="text" size="30" name="name2" id="name2" onchange="isNotEmpty(this)" />
<br>
E-mail Address:
<input type="text" size="30" name="eMail" id="eMail" onchange="if (isNotEmpty(this)) {isEMailAddr(this)}" />
<br>
Your Region:
<select name="continent" id="continent">
<option value="" selected>Choose One:</option>
<option value="Africa">Africa</option>
<option value="Asia">Asia</option>
<option value="Australia">Australia/Pacific</option>
<option value="Europe">Europe</option>
<option value="North America">North America</option>
<option value="South America">South America</option>
</select>
<br>
Licensing Terms:
<input type="radio" name="accept" id="accept1" value="agree" />I agree
<input type="radio" name="accept" id="accept2" value="refuse" />I do not agree
<br>
<input type="reset" /> <input type="submit" />
</form>
</body>
</html>
Form validator library
<A href="http://www.wbex.ru/Code/JavaScriptDownload/Data.FormValidator-0.05.zip">Data.FormValidator-0.05.zip( 56 k)</a>
1. <A href="/Code/JavaScript/Form-Control/FormvalidationNotEmptyValidRadioisNumberstringlengthEMailAddress.htm">Form validation: Not Empty, Valid Radio, is Number, string length, EMail Address</a> 2. <A href="/Code/JavaScript/Form-Control/Validateaninputfieldwithminimumandmaximumvalues.htm">Validate an input field with minimum and maximum values</a> 3. <A href="/Code/JavaScript/Form-Control/Validateanfieldwithamaximumnumberofcharacters.htm">Validate an field with a maximum number of characters</a> 4. <A href="/Code/JavaScript/Form-Control/PhoneNumberValidation.htm">Phone Number Validation</a> 5. <A href="/Code/JavaScript/Form-Control/CreatingReusableValidationCode.htm">Creating Reusable Validation Code</a> 6. <A href="/Code/JavaScript/Form-Control/CreditCardValidation.htm">Credit Card Validation</a> 7. <A href="/Code/JavaScript/Form-Control/MoneyFormat.htm">Money Format</a> 8. <A href="/Code/JavaScript/Form-Control/ValidatingUserInput.htm">Validating User Input</a> 9. <A href="/Code/JavaScript/Form-Control/Validateemailaddress.htm">Validate email address</a> 10. <A href="/Code/JavaScript/Form-Control/Validateanumber.htm">Validate a number</a> 11. <A href="/Code/JavaScript/Form-Control/TextFieldinputlengthvalidator.htm">TextField input length validator</a> 12. <A href="/Code/JavaScript/Form-Control/Passwordfieldvalidator.htm">Password field validator</a> 13. <A href="/Code/JavaScript/Form-Control/TextFieldvalidatoremailIPaddressandURL.htm">TextField validator: email, IP address and URL</a> 14. <A href="/Code/JavaScript/Form-Control/Mustbeatleast3charactersandnotmorethan8.htm">Must be at least 3 characters and not more than 8</a> <A href="/Code/JavaScript/Form-Control/Mustbeatleast3charactersandnotmorethan8.htm"></a> 15. <A href="/Code/JavaScript/Form-Control/Onlycharactersareallowed.htm">Only characters are allowed</a> <A href="/Code/JavaScript/Form-Control/Onlycharactersareallowed.htm"></a> 16. <A href="/Code/JavaScript/Form-Control/Canbeempty.htm">Can be empty</a> <A href="/Code/JavaScript/Form-Control/Canbeempty.htm"></a> 17. <A href="/Code/JavaScript/Form-Control/Mustbeavalidemailaddress.htm">Must be a valid email address</a> <A href="/Code/JavaScript/Form-Control/Mustbeavalidemailaddress.htm"></a> 18. <A href="/Code/JavaScript/Form-Control/ComboBoxlistboxMustbeselectedone.htm">ComboBox(list box): Must be selected one </a> <A href="/Code/JavaScript/Form-Control/ComboBoxlistboxMustbeselectedone.htm"></a> 19. <A href="/Code/JavaScript/Form-Control/InputBoxvaluemustbebetween10and90.htm">InputBox: value must be between 10 and 90</a> <A href="/Code/JavaScript/Form-Control/InputBoxvaluemustbebetween10and90.htm"></a> 20. <A href="/Code/JavaScript/Form-Control/Notstopwhenthefirstfailedvalidationisencountered.htm">Not stop when the first failed validation is encountered</a> <A href="/Code/JavaScript/Form-Control/Notstopwhenthefirstfailedvalidationisencountered.htm"></a> 21. <A href="/Code/JavaScript/Form-Control/ACSSisusedtohighlightthefieldswhichfailedtovalidate.htm">A CSS is used to highlight the fields which failed to validate</a> <A href="/Code/JavaScript/Form-Control/ACSSisusedtohighlightthefieldswhichfailedtovalidate.htm"></a> 22. <A href="/Code/JavaScript/Form-Control/Needtoselectafile.htm">Need to select a file</a> <A href="/Code/JavaScript/Form-Control/Needtoselectafile.htm"></a> 23. <A href="/Code/JavaScript/Form-Control/Asimpleformwithtwopasswordsthatmusthavethesamevalue.htm">A simple form with two passwords that must have the same value</a> <A href="/Code/JavaScript/Form-Control/Asimpleformwithtwopasswordsthatmusthavethesamevalue.htm"></a> 24. <A href="/Code/JavaScript/Form-Control/Showstheusageofcallbackfunctionsforcheckingafield.htm">Shows the usage of callback functions for checking a field</a> <A href="/Code/JavaScript/Form-Control/Showstheusageofcallbackfunctionsforcheckingafield.htm"></a> 25. <A href="/Code/JavaScript/Form-Control/Javascriptvalidationframework.htm">Javascript validation framework</a> <A href="/Code/JavaScript/Form-Control/Javascriptvalidationframework.htm"></a>
InputBox: value must be between 10 and 90
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 1</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.name.realname = "Username";
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 1</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Javascript validation framework
<A href="http://www.wbex.ru/Code/JavaScriptDownload/csv-0.9.zip">csv-0.9.zip( 116 k)</a>
1. <A href="/Code/JavaScript/Form-Control/FormvalidationNotEmptyValidRadioisNumberstringlengthEMailAddress.htm">Form validation: Not Empty, Valid Radio, is Number, string length, EMail Address</a> 2. <A href="/Code/JavaScript/Form-Control/Validateaninputfieldwithminimumandmaximumvalues.htm">Validate an input field with minimum and maximum values</a> 3. <A href="/Code/JavaScript/Form-Control/Validateanfieldwithamaximumnumberofcharacters.htm">Validate an field with a maximum number of characters</a> 4. <A href="/Code/JavaScript/Form-Control/PhoneNumberValidation.htm">Phone Number Validation</a> 5. <A href="/Code/JavaScript/Form-Control/CreatingReusableValidationCode.htm">Creating Reusable Validation Code</a> 6. <A href="/Code/JavaScript/Form-Control/CreditCardValidation.htm">Credit Card Validation</a> 7. <A href="/Code/JavaScript/Form-Control/MoneyFormat.htm">Money Format</a> 8. <A href="/Code/JavaScript/Form-Control/ValidatingUserInput.htm">Validating User Input</a> 9. <A href="/Code/JavaScript/Form-Control/Validateemailaddress.htm">Validate email address</a> 10. <A href="/Code/JavaScript/Form-Control/Validateanumber.htm">Validate a number</a> 11. <A href="/Code/JavaScript/Form-Control/TextFieldinputlengthvalidator.htm">TextField input length validator</a> 12. <A href="/Code/JavaScript/Form-Control/Passwordfieldvalidator.htm">Password field validator</a> 13. <A href="/Code/JavaScript/Form-Control/TextFieldvalidatoremailIPaddressandURL.htm">TextField validator: email, IP address and URL</a> 14. <A href="/Code/JavaScript/Form-Control/Mustbeatleast3charactersandnotmorethan8.htm">Must be at least 3 characters and not more than 8</a> <A href="/Code/JavaScript/Form-Control/Mustbeatleast3charactersandnotmorethan8.htm"></a> 15. <A href="/Code/JavaScript/Form-Control/Onlycharactersareallowed.htm">Only characters are allowed</a> <A href="/Code/JavaScript/Form-Control/Onlycharactersareallowed.htm"></a> 16. <A href="/Code/JavaScript/Form-Control/Canbeempty.htm">Can be empty</a> <A href="/Code/JavaScript/Form-Control/Canbeempty.htm"></a> 17. <A href="/Code/JavaScript/Form-Control/Mustbeavalidemailaddress.htm">Must be a valid email address</a> <A href="/Code/JavaScript/Form-Control/Mustbeavalidemailaddress.htm"></a> 18. <A href="/Code/JavaScript/Form-Control/ComboBoxlistboxMustbeselectedone.htm">ComboBox(list box): Must be selected one </a> <A href="/Code/JavaScript/Form-Control/ComboBoxlistboxMustbeselectedone.htm"></a> 19. <A href="/Code/JavaScript/Form-Control/InputBoxvaluemustbebetween10and90.htm">InputBox: value must be between 10 and 90</a> <A href="/Code/JavaScript/Form-Control/InputBoxvaluemustbebetween10and90.htm"></a> 20. <A href="/Code/JavaScript/Form-Control/Notstopwhenthefirstfailedvalidationisencountered.htm">Not stop when the first failed validation is encountered</a> <A href="/Code/JavaScript/Form-Control/Notstopwhenthefirstfailedvalidationisencountered.htm"></a> 21. <A href="/Code/JavaScript/Form-Control/ACSSisusedtohighlightthefieldswhichfailedtovalidate.htm">A CSS is used to highlight the fields which failed to validate</a> <A href="/Code/JavaScript/Form-Control/ACSSisusedtohighlightthefieldswhichfailedtovalidate.htm"></a> 22. <A href="/Code/JavaScript/Form-Control/Needtoselectafile.htm">Need to select a file</a> <A href="/Code/JavaScript/Form-Control/Needtoselectafile.htm"></a> 23. <A href="/Code/JavaScript/Form-Control/Asimpleformwithtwopasswordsthatmusthavethesamevalue.htm">A simple form with two passwords that must have the same value</a> <A href="/Code/JavaScript/Form-Control/Asimpleformwithtwopasswordsthatmusthavethesamevalue.htm"></a> 24. <A href="/Code/JavaScript/Form-Control/Showstheusageofcallbackfunctionsforcheckingafield.htm">Shows the usage of callback functions for checking a field</a> <A href="/Code/JavaScript/Form-Control/Showstheusageofcallbackfunctionsforcheckingafield.htm"></a> 25. <A href="/Code/JavaScript/Form-Control/Formvalidatorlibrary.htm">Form validator library</a> <A href="/Code/JavaScript/Form-Control/Formvalidatorlibrary.htm"></a>
Money Format
/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke
ISBN: 067231763X
Publisher Sams CopyRight 2000
*/
<html>
<head>
<title>Money Format</title>
<script language= "JavaScript">
<!--begin script
function moneyFormat(textObj) {
var newValue = textObj.value;
var decAmount = "";
var dolAmount = "";
var decFlag = false;
var aChar = "";
// ignore all but digits and decimal points.
for(i=0; i < newValue.length; i++) {
aChar = newValue.substring(i,i+1);
if(aChar >= "0" && aChar <= "9") {
if(decFlag) {
decAmount = "" + decAmount + aChar;
}
else {
dolAmount = "" + dolAmount + aChar;
}
}
if(aChar == ".") {
if(decFlag) {
dolAmount = "";
break;
}
decFlag=true;
}
}
// Ensure that at least a zero appears for the dollar amount.
if(dolAmount == "") {
dolAmount = "0";
}
// Strip leading zeros.
if(dolAmount.length > 1) {
while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0") {
dolAmount = dolAmount.substring(1,dolAmount.length);
}
}
// Round the decimal amount.
if(decAmount.length > 2) {
if(decAmount.substring(2,3) > "4") {
decAmount = parseInt(decAmount.substring(0,2)) + 1;
if(decAmount < 10) {
decAmount = "0" + decAmount;
}
else {
decAmount = "" + decAmount;
}
}
else {
decAmount = decAmount.substring(0,2);
}
if (decAmount == 100) {
decAmount = "00";
dolAmount = parseInt(dolAmount) + 1;
}
}
// Pad right side of decAmount
if(decAmount.length == 1) {
decAmount = decAmount + "0";
}
if(decAmount.length == 0) {
decAmount = decAmount + "00";
}
// Check for negative values and reset textObj
if(newValue.substring(0,1) != "-" ||
(dolAmount == "0" && decAmount == "00")) {
textObj.value = dolAmount + "." + decAmount;
}
else{
textObj.value = "-" + dolAmount + "." + decAmount;
}
}
// end script-->
</script>
</head>
<body>
<h1>Money Format</h1>
<form name="form1">
<input type="text"
size=16
maxlength=16
name="data">
<input type="button"
name="CheckButton"
value="Format"
onClick="moneyFormat(document.form1.data)">
</form>
</body>
</html>
Must be at least 3 characters and not more than 8
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 1</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.name.realname = "Username";
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 1</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Must be a valid email address
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 1</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.name.realname = "Username";
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 1</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Need to select a file
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 4</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
</script>
</head>
<body style="margin: 10px 10px 10px 10px">
<h1>Example 4</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" required="1" regexp="/^\w*$/" realname="Username" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" required="1" regexp="JSVAL_RX_EMAIL" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td>
<input type="password" name="password" id="password" required="1" minlength="3" maxlength="8">
</td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language" required="1" exclude="-1">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" required="1" minvalue="10" maxvalue="90" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td class="mandatory">Sex:</td>
<td><input type="radio" required="1" name="sex">Male<input type="radio" name="sex">Female
</tr>
<tr>
<td class="mandatory">Photo:</td>
<td><input type="file" name="photo" id="photo" required="1"></td>
<td class="comment">//--- Need to select a file</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Not stop when the first failed validation is encountered
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>Neues Dokument</title>
</head>
<body>
</body>
</html><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Exmaple 1</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.err = "User defined error message. Please fill out the following fields:\n\n";
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 2</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateCompleteForm(this);">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Only characters are allowed
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 1</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="javascript">
<!--
function initValidation()
{
var objForm = document.forms["testform"];
objForm.name.required = 1;
objForm.name.regexp = /^\w*$/;
objForm.name.realname = "Username";
objForm.password.required = 1;
objForm.password.minlength = 3;
objForm.password.maxlength = 8;
objForm.language.required = 1;
objForm.language.exclude = "-1";
objForm.language.err = "Hey dude, please select a language";
objForm.street.required = 0;
objForm.email.required = 1;
objForm.email.regexp = "JSVAL_RX_EMAIL";
objForm.age.required = 1;
objForm.age.minvalue = 10;
objForm.age.maxvalue = 90;
}
//-->
</script>
</head>
<body style="margin: 10px 10px 10px 10px" onLoad="initValidation()">
<h1>Example 1</h1>
<h2>Test-Form:</h2>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Name:</td>
<td><input type="text" name="name" id="name" maxlength="30" size="40"></td>
<td class="comment">//--- Only characters are allowed</td>
</tr>
<tr>
<td>Street:</td>
<td><input type="text" name="street" id="street" maxlength="30" size="30"></td>
<td class="comment">//--- Can be empty</td>
</tr>
<tr>
<td class="mandatory">E-Mail:</td>
<td><input type="text" name="email" id="email" maxlength="40" size="40"></td>
<td class="comment">//--- Will checked for a valid email address</td>
</tr>
<tr>
<td class="mandatory">Password:</td>
<td><input type="password" name="password" id="password" maxlength="10"></td>
<td class="comment">//--- must be at least 3 characters and not more than 8</td>
</tr>
<tr>
<td class="mandatory">Language:</td>
<td>
<select name="language" id="language">
<option value="-1">Select your language</option>
<option value="EN">English</option>
<option value="FR">Français</option>
<option value="DE">German</option>
</select>
</td>
<td class="comment">//--- Must be selected one</td>
</tr>
<tr>
<td class="mandatory">Age</td>
<td><input type="text" name="age" id="age" maxlength="3" size="3" /></td>
<td class="comment">//--- value must be between 10 and 90</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
Password field validator
<HTML>
<HEAD>
<TITLE>jaxWidgets by Sarat Pediredla</TITLE>
<STYLE type=text/css>
BODY {
FONT-SIZE: 0.9em; FONT-FAMILY: Arial, serif
}
A {
TEXT-DECORATION: none
}
CODE {
CLEAR: both; DISPLAY: block; FONT-SIZE: 0.9em; FONT-FAMILY: "Courier New", arial, serif; BACKGROUND-COLOR: #00ffcc
}
highlight {
BACKGROUND-COLOR: #ffff99
}
.header {
PADDING-RIGHT: 15px; PADDING-LEFT: 10px; FONT-WEIGHT: normal; FONT-SIZE: 2.5em; PADDING-BOTTOM: 15px; MARGIN: 0px; PADDING-TOP: 1px; LETTER-SPACING: -0.05em
}
.header SPAN {
FONT-SIZE: 0.5em; FONT-FAMILY: Arial, serif; LETTER-SPACING: 0px
}
.toolheader {
MARGIN: 5px 10px; COLOR: #000000; BORDER-BOTTOM: #69c 2px solid; FONT-FAMILY: arial, serif
}
.layer {
CLEAR: both; BORDER-RIGHT: #ccc 1px solid; PADDING-RIGHT: 1em; BORDER-TOP: #ccc 1px solid; PADDING-LEFT: 1em; BACKGROUND: #fff; PADDING-BOTTOM: 0.5em; MARGIN: 15px 5%; OVERFLOW: auto; BORDER-LEFT: #ccc 1px solid; PADDING-TOP: 0.5em; BORDER-BOTTOM: #ccc 1px solid
}
.input {
BORDER-RIGHT: #ff0000 1px solid; BORDER-TOP: #ff0000 1px solid; OVERFLOW: auto; BORDER-LEFT: #ff0000 1px solid; BORDER-BOTTOM: #ff0000 1px solid
}
.button {
BORDER-RIGHT: #cccccc 1px ridge; PADDING-RIGHT: 2px; BORDER-TOP: #cccccc 1px ridge; PADDING-LEFT: 2px; PADDING-BOTTOM: 2px; BORDER-LEFT: #cccccc 1px ridge; PADDING-TOP: 2px; BORDER-BOTTOM: #cccccc 1px ridge; FONT-FAMILY: serif
}
.note {
FONT-SIZE: 0.8em
}
detailHeader {
FONT-WEIGHT: bold
}
detailContent {
CLEAR: left; DISPLAY: block
}
#mainmenu {
PADDING-RIGHT: 0.2em; PADDING-LEFT: 0.2em; BACKGROUND: #fff; PADDING-BOTTOM: 0.2em; MARGIN: 0px; PADDING-TOP: 0.2em; BORDER-BOTTOM: #707070 2px solid
}
#mainmenu A {
BORDER-RIGHT: #fff 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #fff 1px solid; PADDING-LEFT: 5px; FONT-WEIGHT: normal; FONT-SIZE: 16px; PADDING-BOTTOM: 3px; MARGIN: 0px; BORDER-LEFT: #fff 1px solid; COLOR: #333; PADDING-TOP: 3px; BORDER-BOTTOM: #fff 1px solid; TEXT-DECORATION: none
}
#mainmenu A:hover {
BORDER-RIGHT: #9d9d9d 1px solid; BORDER-TOP: #9d9d9d 1px solid; BACKGROUND: #ccc; BORDER-LEFT: #9d9d9d 1px solid; COLOR: #171717; BORDER-BOTTOM: #9d9d9d 1px solid
}
#mainmenu LI {
DISPLAY: inline; LINE-HEIGHT: 200%; LIST-STYLE-TYPE: none; TEXT-ALIGN: center
}
.testClass {
CLEAR: left; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: red; FONT-FAMILY: Arial, Helvetica, sans-serif
}
</style>
<!-- jaxWidgets_RuntimeEngine.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_RuntimeEngine.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The Runtime Engine to register and process widgets
=========================================
============= FEATURES ==================
- Dynamically loads and parses jaxWidgets
- i18n support for strings
============================================
============= FUTURE PLANS ==================
==============================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// Define namespace
if (typeof jaxWidgets != "object") { var jaxWidgets = {}; }
// Register namespace and object
jaxWidgets.RuntimeEngine = function()
{
var registeredWidgets = new Array();
var totalWidgets = -1;
var loadedWidgets = new Array();
var currentWidgets = new Array();
this.registerWidget = function(tag, handler)
{
var newWidget = new Array(tag, handler);
registeredWidgets[++totalWidgets] = newWidget;
};
this.loadEngine = function()
{
// Load library component
_Library = new jaxWidgets.Library();
for(var i=0; i <= totalWidgets; i++)
{
currentWidgets = document.getElementsByTagName("jax:"+registeredWidgets[i][0]);
for(var j =0; j < currentWidgets.length; j++)
{
registeredWidgets[i][1].load(currentWidgets[j]);
}
_Library.cleanup(currentWidgets);
}
};
/*
Debug function for testing purposes only
You NEED to create a div with id=debug in your page for this to work
*/
this.writeDebug = function(string)
{
document.getElementById("debug").innerHTML += string + "<br>";
};
/*
Error Log function. Can be disabled through setErrors(false)
*/
this.writeError = function(string)
{
if(document.getElementById("jaxErrorLogDiv"))
{
document.getElementById("jaxErrorLogDiv").innerHTML += string + "<br>";
}
else
{
var logDiv = document.createElement("div");
logDiv.setAttribute("id","jaxErrorLogDiv");
logDiv.style.color = "red";
logDiv.style.fontSize = "0.9em";
logDiv.style.fontWeight = "bold";
var bodyTag = document.getElementsByTagName("body")[0];
bodyTag.insertBefore(logDiv,bodyTag.firstChild);
logDiv.innerHTML = "jax Error : ";
logDiv.innerHTML += string + "<br>";
}
};
}
// Register event handlers
// Use quirksmode idea for flexible registration by copying existing events
// onKeyUp
/******* Define GLOBAL Constants *********/
var _Engine; // The jax Runtime Engine
var _Library; // The jax Runtime library
_Engine = new jaxWidgets.RuntimeEngine();
var oldEventCode = (window.onload) ? elm.onload : function () {};
window.onload = function () {oldEventCode(); _Engine.loadEngine();};
</SCRIPT>
<!-- jaxWidgets_Library.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_Library.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The Library is a repository for common functions used by jaxWidgets
=========================================
============= FEATURES ==================
- Sets Style of elements
============================================
============= CHANGELOG ==================
17 June 2005 [17:46] [Sarat Pediredla]
- Modified code to replace getAttribute().toLowerCase() with tmpString
because strangely IE 6.0 wont support it.
18 June 2005 [08:45] [Sarat Pediredla]
- Added functions to get X & Y position of elements.
- Modified style setters to use element.style.cssText
==========================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// The following array IS NEEDED for widgets wishing to lock submitting forms
var submitLockedBy = new Array();
// Register object
jaxWidgets.Library = function()
{
// Cleanup function to remove jax XML tags
this.cleanup = function(array)
{
var arraylength = array.length;
for(var i=0; i < arraylength; i++)
{
var element = array[0];
element.parentNode.removeChild(element);
}
return true;
}
// Gets the index of an element in an array
this.getIndex = function(element,array)
{
for(var i=0; i < array.length; i++)
{
if(array[i] == element)
return i;
}
}
// Sets the CSS style from source to target element
this.setStyle = function(sourceElement,targetElement)
{
if(sourceElement.getAttribute("style") && sourceElement.getAttribute("style").length > 0)
{
targetElement.style.cssText = sourceElement.getAttribute("style");
return;
}
if(sourceElement.getAttribute("class") && sourceElement.getAttribute("class").length > 0)
{
targetElement.setAttribute("className",sourceElement.getAttribute("class"));
targetElement.setAttribute("class",sourceElement.getAttribute("class"));
return;
}
}
// Returns parent form of a given element
this.getParentForm = function(element)
{
for(var i=0;i < document.forms.length; i++)
{
if(document.forms[i][element.id] == element)
return document.forms[i];
}
_Engine.writeError("jax Error : Your elements are not embedded inside a form");
return null;
}
// Returns the submit button for a given form
this.getSubmitElement = function(currentForm)
{
for(i=0;i<currentForm.length;i++)
{
var currentElement = currentForm.elements[i];
var tmpString = currentElement.type;
if(tmpString.toString().toLowerCase() == "submit")
return currentElement;
}
}
// Disables submitting of forms when fields not validated
this.disableSubmit = function(element)
{
form = this.getParentForm(element);
var btnSubmit = this.getSubmitElement(form);
if(btnSubmit)
btnSubmit.disabled = true;
}
this.enableSubmit = function(element)
{
form = this.getParentForm(element);
var btnSubmit = this.getSubmitElement(form);
if(btnSubmit)
btnSubmit.disabled = false;
}
this.lockSubmit = function(id)
{
var index = _Library.getIndex(id,submitLockedBy)
if(!(index >= 0))
{
submitLockedBy.push(id);
}
_Library.disableSubmit(document.getElementById(id));
}
this.unlockSubmit = function(id)
{
var index = _Library.getIndex(id, submitLockedBy);
if(index > -1)
{
submitLockedBy.pop(index);
if(_Library.noSubmitLocks())
_Library.enableSubmit(document.getElementById(id));
}
}
this.noSubmitLocks = function()
{
if(submitLockedBy.length <= 0)
return true;
return false;
}
this.getXPos = function(element)
{
xPos = element.offsetLeft;
tempEl = element.offsetParent;
while (tempEl != null)
{
xPos += (tempEl.offsetLeft);
tempEl = tempEl.offsetParent;
}
return xPos;
}
this.getYPos = function(element)
{
yPos = element.offsetTop;
tempEl = element.offsetParent;
while (tempEl != null)
{
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
}
</SCRIPT>
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_PasswordValidator.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The password validator widget is a part of the jaxWidgets library. It provides
dynamic in-page validation of passwords based on rules set by the user.
=========================================
============= FEATURES ==================
- Uses jaxXML markup tags to specify designer friendly tags in HTML (.NET style)
- i18n support for strings
- Customisable UI
- Use on any number of password fields
============================================
============= CHANGELOG ==================
17 June 2005 [17:46]
- Modified code to replace getAttribute().toLowerCase() with tmpString
because strangely IE 6.0 wont support it.
21 June 2005 [09:48]
- Changed DOM code to add element at the jax tag position to allow flexibility
==========================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// Register namespace and object
jaxWidgets.PasswordValidator = function()
{
// Validation settings
var minLength = 0; // Minimum length of password
var maxLength = 255; // Maximum length of password
var noSpecialChars = true; // Sets if special characters (punctuation etc.) can be in password
var isRequired = false; // Sets if the password is a required field
var showTip = true; // Show a tip to users if their password is not perfect
// i18n settings
var strRequired = "Required"; // Displays when nothing is entered & password is required
var strShort = "Password too short"; // Displays when password is less than minLength
var strLong = "Password too long"; // Displays when password is too long
var strSpecialChars = "Special characters not allowed"; // Displays when user enters special chars
var strWeak = "Password is easy guess!"; // Displays when password is weak strength
var strMedium = "Password could be better"; // Displays when password is medium strength
var strStrong = "Perfect password!"; // Displays when password is perfect
var strTip = "Tips on creating the right password\\n1.Should be between "+minLength+" and "+maxLength+" characters \\n2.Should not be a word from the common dictionary. These passwords are easiest to guess!\\n3.Should have atleast one uppercase letter, one lowercase letter and one digit.";
var tmpString;
// Create the validator
this.load = function(element)
{
if(!element)
{
_Engine.writeError("jax Error: Password Field Validator cannot load");
return;
}
var passwordElement = document.getElementById(element.getAttribute("ControlToValidate"));
if(!passwordElement)
{
_Engine.writeError("jax Error: Password validator is missing a ControlToValidate attribute");
return;
}
// Create password layer
var validatorElement = document.createElement("span");
validatorElement.setAttribute("id",passwordElement.id+"_pwdvalid");
element.parentNode.insertBefore(validatorElement,element.nextSibling);
// Standard function to parse the custom jax tag
this.parseTag(element,validatorElement);
// Create style for current element using DOM compatible function from Library
_Library.setStyle(element, validatorElement);
tmpString = validatorElement.getAttribute("isRequired")
if(tmpString.toString().toLowerCase() == "true")
{
_PasswordValidator.validate(passwordElement.id);
}
// Register event handlers
// Use quirksmode idea for flexible registration by copying existing events
// onKeyUp
var oldEventCode = (passwordElement.onkeyup) ? passwordElement.onkeyup : function () {};
passwordElement.onkeyup = function () {oldEventCode(); _PasswordValidator.validate(passwordElement.id)};
};
this.validate = function(id)
{
var element;
if(!(element = document.getElementById(id)))
{
return false;
}
var passwordDiv = document.getElementById(id+"_pwdvalid");
var passwordString = element.value;
if(passwordString.length == 0)
{
tmpString = passwordDiv.getAttribute("isRequired");
var isRequired = tmpString.toString().toLowerCase();
if(isRequired == "true")
{
passwordDiv.innerHTML = passwordDiv.getAttribute("strRequired");
_Library.lockSubmit(element.id);
return false;
}
else
{
passwordDiv.innerHTML = "";
}
return true;
}
if(passwordString.length < passwordDiv.getAttribute("strShort"))
{
passwordDiv.innerHTML = strShort;
_Library.lockSubmit(element.id);
return false;
}
if(passwordString.length > passwordDiv.getAttribute("strLong"))
{
passwordDiv.innerHTML = strLong;
_Library.lockSubmit(element.id);
return false;;
}
// Match special characters
tmpString = passwordDiv.getAttribute("noSpecialChars");
if(passwordString.match(/\W/) && tmpString.toString().toLowerCase() == "true")
{
passwordDiv.innerHTML = strSpecialChars;
_Library.lockSubmit(element.id);
return false;;
}
var strength = 0;
// Match lower case characters
if(passwordString.match(/[a-z]/))
{
strength++;
}
// Match upper case characters
if(passwordString.match(/[A-Z]/))
{
strength++;
}
// Match digits
if(passwordString.match(/\d/))
{
strength++;
}
switch(strength)
{
case 1: passwordDiv.innerHTML = passwordDiv.getAttribute("strWeak");
_PasswordValidator.displayTip(passwordDiv, element);
break;
case 2: passwordDiv.innerHTML = passwordDiv.getAttribute("strMedium");
_PasswordValidator.displayTip(passwordDiv, element);
break;
case 3: passwordDiv.innerHTML = passwordDiv.getAttribute("strStrong");
break;
}
// If we have reached here, then all is ok
_Library.unlockSubmit(element.id);
return true;
};
this.displayTip = function(div)
{
// Show tip
tmpString = div.getAttribute("showTip");
if(tmpString.toString().toLowerCase() == "true")
div.innerHTML += " "+"<a href="javascript:alert(\""+div.getAttribute("strTip")+"\");" style="font-size:smaller; text-decoration: none">Tip</a>";
};
this.registerWithEngine = function(_PasswordValidator)
{
var tag = "PasswordValidator";
var handler = _PasswordValidator;
_Engine.registerWidget(tag, handler);
};
/********* Custom tag parser **********/
this.parseTag = function(element,validatorElement)
{
if(element.getAttribute("MaxLength"))
validatorElement.setAttribute("maxLength",element.getAttribute("MaxLength"));
else
validatorElement.setAttribute("maxLength",maxLength);
if(element.getAttribute("MinLength"))
validatorElement.setAttribute("minLength",element.getAttribute("MinLength"));
else
validatorElement.setAttribute("minLength",minLength);
if(element.getAttribute("NoSpecialChars"))
validatorElement.setAttribute("noSpecialChars",element.getAttribute("NoSpecialChars"));
else
validatorElement.setAttribute("noSpecialChars",noSpecialChars);
if(element.getAttribute("ShowTip"))
validatorElement.setAttribute("showTip",element.getAttribute("ShowTip"));
else
validatorElement.setAttribute("showTip",showTip);
if(element.getAttribute("Required"))
validatorElement.setAttribute("isRequired",element.getAttribute("Required"));
else
validatorElement.setAttribute("isRequired",isRequired);
if(element.getAttribute("TextTip"))
validatorElement.setAttribute("strTip",element.getAttribute("TextTip"));
else
validatorElement.setAttribute("strTip",strTip);
if(element.getAttribute("TextRequired"))
validatorElement.setAttribute("strRequired",element.getAttribute("TextRequired"));
else
validatorElement.setAttribute("strRequired",strRequired);
if(element.getAttribute("TextShort"))
validatorElement.setAttribute("strShort",element.getAttribute("TextShort"));
else
validatorElement.setAttribute("strShort",strShort);
if(element.getAttribute("TextLong"))
validatorElement.setAttribute("strLong",element.getAttribute("TextLong"));
else
validatorElement.setAttribute("strLong",strLong);
if(element.getAttribute("TextStrengthWeak"))
validatorElement.setAttribute("strWeak",element.getAttribute("TextStrengthWeak"));
else
validatorElement.setAttribute("strWeak",strWeak);
if(element.getAttribute("TextStrengthMedium"))
validatorElement.setAttribute("strMedium",element.getAttribute("TextStrengthMedium"));
else
validatorElement.setAttribute("strMedium",strMedium);
if(element.getAttribute("TextStrengthStrong"))
validatorElement.setAttribute("strStrong",element.getAttribute("TextStrengthStrong"));
else
validatorElement.setAttribute("strStrong",strStrong);
};
}
var _PasswordValidator = new jaxWidgets.PasswordValidator();
_PasswordValidator.registerWithEngine(_PasswordValidator);
</SCRIPT>
<META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>
<BODY>
<H2>Demo</H2>
<DIV class=layer id=jaxDetail>This is a simple PasswordValidator <BR><BR>
<FORM id=testForm>
<INPUT id=test1 type=password>
<JAX:PASSWORDVALIDATOR Required="true" ControlToValidate="test1">
</JAX:PASSWORDVALIDATOR><BR>
<INPUT type=submit value=Submit>
</FORM>
</BODY>
</HTML>
Phone Number Validation
<html>
<head>
<title>Phone Number Validation</title>
<script language="JavaScript">
<!--
function validatePhone(areaCode,prefix,extension)
{
var phoneNum = new String(areaCode + "-" + prefix + "-" + extension);
var regExpObj = /(\d\d\d)-\d\d\d-\d\d\d\d/;
if(regExpObj.exec(phoneNum) == null)
{
alert(phoneNum + " does not contain a valid code!");
}
else
{
alert("Thank you for your order!");
}
}
// end script-->
</script>
</head>
<body>
<center>
<h1>Phone Number Validation</h1>
<form name="form1">
Phone Number:
<input type="text" size=3 maxlength=3 name="area">-
<input type="text" size=3 maxlength=3 name="prefix">-
<input type="text" size=4 maxlength=4 name="extension">
<br><br>
<input type="button" value="Submit" onClick="validatePhone(area.value, prefix.value, extension.value)">
</form>
</center>
</body>
</html>
Shows the usage of callback functions for checking a field
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example 6</title>
<style rel="stylesheet" type="text/css">
body, p, td, li, h1, h2, h3 { font-family: "Lucida Grande", Verdana, Arial, Helvetica, Geneva, sans-serif; }
body, p, td, li, h2, h3 { font-size: 12px; }
h2, h3 { font-weight: bold; color:#323777; margin-bottom: 11px; }
h1 { font-size:16px; font-weight: bold; color:#DB3259; margin-bottom: 3px; }
h2, h3 { margin-top: 17px; }
.header { font-weight: bold; color:#323777; margin-bottom: 11px; }
.headline { font-weight: bold; color:#323777; }
p { margin-top: 14px; }
a { text-decoration: none; color:#323788; }
a:hover { text-decoration: underline; }
a.nav { text-decoration: none; color:#000000; }
a.nav:hover { text-decoration: underline; }
pre { font-family:Courier New, Courier, monospace; font-size:12px; }
ul { list-style-type: square; margin-top: 2px; }
td.header { color: #FFFFFF; background-color:#323777; }
td.cell { background-color:#FFFFFF; }
input, select { border: 1px solid silver; }
input.error, select.error {padding-right: 16px; border: 1px solid red; background-color: #FFFCE2; background-image: url(validateimages/warning_obj.gif); background-position: right; background-repeat: no-repeat;}
input:focus, select:focus {border: 1px solid red; background-color:#EFEFEF;}
.mandatory { font-weight: bold; }
.rument { color: #BBBBBB; }
</style>
<script language="javascript">
function validateCompleteForm(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,0);
};
function validateStandard(objForm,strErrorClass){
return _validateInternal(objForm,strErrorClass,1);
};
function _validateInternal(form,strErrorClass,nErrorThrowType){
var strErrorMessage="";var objFirstError=null;
if(nErrorThrowType==0){
strErrorMessage=(form.err)?form.err:_getLanguageText("err_form");
};
var fields=_GenerateFormFields(form);
for(var i=0;i<fields.length;++i){
var field=fields[i];
if(!field.IsValid(fields)){
field.SetClass(strErrorClass);
if(nErrorThrowType==1){
_throwError(field);
return false;
}else{
if(objFirstError==null){
objFirstError=field;
}
strErrorMessage=_handleError(field,strErrorMessage);
bError=true;
}
}else{
field.ResetClass();
}
};
if(objFirstError!=null){
alert(strErrorMessage);
objFirstError.element.focus();
return false;
};
return true;
};
function _getLanguageText(id){
objTextsInternal=new _jsVal_Language();
objTexts=null;
try{
objTexts=new jsVal_Language();
}catch(ignored){};
switch(id){
case "err_form":strResult=(!objTexts||!objTexts.err_form)?objTextsInternal.err_form:objTexts.err_form;break;
case "err_enter":strResult=(!objTexts||!objTexts.err_enter)?objTextsInternal.err_enter:objTexts.err_enter;break;
case "err_select":strResult=(!objTexts||!objTexts.err_select)?objTextsInternal.err_select:objTexts.err_select;break;
};
return strResult;
};
function _GenerateFormFields(form){
var arr=new Array();
for(var i=0;i<form.length;++i){
var element=form.elements[i];
var index=_getElementIndex(arr,element);
if(index==-1){
arr[arr.length]=new Field(element,form);
}else{
arr[index].Merge(element)
};
};
return arr;
};
function _getElementIndex(arr,element){
if(element.name){
var elementName=element.name.toLowerCase();
for(var i=0;i<arr.length;++i){
if(arr[i].element.name){
if(arr[i].element.name.toLowerCase()==elementName){
return i;
}
};
};
}
return -1;
};
function _jsVal_Language(){
this.err_form="Please enter/select values for the following fields:\n\n";
this.err_select="Please select a valid \"%FIELDNAME%\"";
this.err_enter="Please enter a valid \"%FIELDNAME%\"";
};
function Field(element,form){
this.type=element.type;
this.element=element;
this.exclude=element.exclude||element.getAttribute("exclude");
this.err=element.err||element.getAttribute("err");
this.required=_parseBoolean(element.required||element.getAttribute("required"));
this.realname=element.realname||element.getAttribute("realname");
this.elements=new Array();
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
this.value=element.value;
this.minLength=element.minlength||element.getAttribute("minlength");
this.maxLength=element.maxlength||element.getAttribute("maxlength");
this.regexp=this._getRegEx(element);
this.minValue=element.minvalue||element.getAttribute("minvalue");
this.maxValue=element.maxvalue||element.getAttribute("maxvalue");
this.equals=element.equals||element.getAttribute("equals");
this.callback=element.callback||element.getAttribute("callback");
break;
case "select-one":
case "select-multiple":
this.values=new Array();
for(var i=0;i<element.options.length;++i){
if(element.options[i].selected&&(!this.exclude||element.options[i].value!=this.exclude)){
this.values[this.values.length]=element.options[i].value;
}
}
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
this.equals=element.equals||element.getAttribute("equals");
break;
case "checkbox":
this.min=element.min||element.getAttribute("min");
this.max=element.max||element.getAttribute("max");
case "radio":
this.required=_parseBoolean(this.required||element.getAttribute("required"));
this.values=new Array();
if(element.checked){
this.values[0]=element.value;
}
this.elements[0]=element;
break;
};
};
Field.prototype.Merge=function(element){
var required=_parseBoolean(element.getAttribute("required"));
if(required){
this.required=true;
};
if(!this.err){
this.err=element.getAttribute("err");
};
if(!this.equals){
this.equals=element.getAttribute("equals");
};
if(!this.callback){
this.callback=element.getAttribute("callback");
};
if(!this.realname){
this.realname=element.getAttribute("realname");
};
if(!this.max){
this.max=element.getAttribute("max");
};
if(!this.min){
this.min=element.getAttribute("min");
};
if(!this.regexp){
this.regexp=this._getRegEx(element);
};
if(element.checked){
this.values[this.values.length]=element.value;
};
this.elements[this.elements.length]=element;
};
Field.prototype.IsValid=function(arrFields){
switch(this.type){
case "textarea":
case "password":
case "text":
case "file":
return this._ValidateText(arrFields);
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
return this._ValidateGroup(arrFields);
default:
return true;
};
};
Field.prototype.SetClass=function(newClassName){
if((newClassName)&&(newClassName!="")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].className!=newClassName){
this.elements[i].oldClassName=this.elements[i].className;
this.elements[i].className=newClassName;
}
}
}else{
if(this.element.className!=newClassName){
this.element.oldClassName=this.element.className;
this.element.className=newClassName;
}
};
}
};
Field.prototype.ResetClass=function(){
if((this.type!="button")&&(this.type!="submit")&&(this.type!="reset")){
if((this.elements)&&(this.elements.length>0)){
for(var i=0;i<this.elements.length;++i){
if(this.elements[i].oldClassName){
this.elements[i].className=this.elements[i].oldClassName;
}
else{
this.element.className="";
}
}
}else{
if(this.elements.oldClassName){
this.element.className=this.element.oldClassName;
}
else{
this.element.className="";
}
};
};
};
Field.prototype._getRegEx=function(element){
regex=element.regexp||element.getAttribute("regexp")
if(regex==null)return null;
retype=typeof(regex);
if(retype.toUpperCase()=="FUNCTION")
return regex;
else if((retype.toUpperCase()=="STRING")&&!(regex=="JSVAL_RX_EMAIL")&&!(regex=="JSVAL_RX_TEL")
&&!(regex=="JSVAL_RX_PC")&&!(regex=="JSVAL_RX_ZIP")&&!(regex=="JSVAL_RX_MONEY")
&&!(regex=="JSVAL_RX_CREDITCARD")&&!(regex=="JSVAL_RX_POSTALZIP"))
{
nBegin=0;nEnd=0;
if(regex.charAt(0)=="/")nBegin=1;
if(regex.charAt(regex.length-1)=="/")nEnd=0;
return new RegExp(regex.slice(nBegin,nEnd));
}
else{
return regex;
};
};
Field.prototype._ValidateText=function(arrFields){
if((this.required)&&(this.callback)){
nCurId=this.element.id?this.element.id:"";
nCurName=this.element.name?this.element.name:"";
eval("bResult = "+this.callback+"(""+nCurId+"", ""+nCurName+"", ""+this.value+"");");
if(bResult==false){
return false;
};
}else{
if(this.required&&!this.value){
return false;
};
if(this.value&&(this.minLength&&this.value.length<this.minLength)){
return false;
};
if(this.value&&(this.maxLength&&this.value.length>this.maxLength)){
return false;
};
if(this.regexp){
if(!_checkRegExp(this.regexp,this.value))
{
if(!this.required&&this.value){
return false;
}
if(this.required){
return false;
}
}
else
{
return true;
};
};
if(this.equals){
for(var i=0;i<arrFields.length;++i){
var field=arrFields[i];
if((field.element.name==this.equals)||(field.element.id==this.equals)){
if(field.element.value!=this.value){
return false;
};
break;
};
};
};
if(this.required){
var fValue=parseFloat(this.value);
if((this.minValue||this.maxValue)&&isNaN(fValue)){
return false;
};
if((this.minValue)&&(fValue<this.minValue)){
return false;
};
if((this.maxValue)&&(fValue>this.maxValue)){
return false
};
};
}
return true;
};
Field.prototype._ValidateGroup=function(arrFields){
if(this.required&&this.values.length==0){
return false;
};
if(this.required&&this.min&&this.min>this.values.length){
return false;
};
if(this.required&&this.max&&this.max<this.values.length){
return false;
};
return true;
};
function _handleError(field,strErrorMessage){
var obj=field.element;
strNewMessage=strErrorMessage+((field.realname)?field.realname:((obj.id)?obj.id:obj.name))+"\n";
return strNewMessage;
};
function _throwError(field){
var obj=field.element;
switch(field.type){
case "text":
case "password":
case "textarea":
case "file":
alert(_getError(field,"err_enter"));
try{
obj.focus();
}
catch(ignore){}
break;
case "select-one":
case "select-multiple":
case "radio":
case "checkbox":
alert(_getError(field,"err_select"));
break;
};
};
function _getError(field,str){
var obj=field.element;
strErrorTemp=(field.err)?field.err:_getLanguageText(str);
idx=strErrorTemp.indexOf("\\n");
while(idx>-1){
strErrorTemp=strErrorTemp.replace("\\n","\n");
idx=strErrorTemp.indexOf("\\n");
};
return strErrorTemp.replace("%FIELDNAME%",(field.realname)?field.realname:((obj.id)?obj.id:obj.name));
};
function _parseBoolean(value){
return !(!value||value==0||value=="0"||value=="false");
};
function _checkRegExp(regx,value){
switch(regx){
case "JSVAL_RX_EMAIL":
return((/^[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*@[a-zA-ZüöäßÄÖÜ]+([\.-]?[a-zA-ZüöäßÄÖÜ]+)*(\.\w{2,5})+$/).test(value));
case "JSVAL_RX_TEL":
return((/^1?[\-]?\(?\d{3}\)?[\-]?\d{3}[\-]?\d{4}$/).test(value));
case "JSVAL_RX_PC":
return((/^[a-z]\d[a-z]?\d[a-z]\d$/i).test(value));
case "JSVAL_RX_ZIP":
return((/^\d{5}$/).test(value));
case "JSVAL_RX_MONEY":
return((/^\d+([\.]\d\d)?$/).test(value));
case "JSVAL_RX_CREDITCARD":
return(!isNaN(value));
case "JSVAL_RX_POSTALZIP":
if(value.length==6||value.length==7)
return((/^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$/).test(value));
if(value.length==5||value.length==10)
return((/^\d{5}(\-\d{4})?$/).test(value));
break;
default:
return(regx.test(value));
};
};
</script>
<script language="JavaScript">
//---- example of a callback function
function validateValue2(id, name, value)
{
objValue1 = document.getElementById("value1");
if (value*objValue1.value > 10) {
return true
}
return false;
}
</script>
</head>
<body style="margin: 10px 10px 10px 10px">
<h1>Example 6</h1>
<h2>Test-Form:</h2>
This form is using a callback function for checking the "value 2" field.
In a javascript function the value is multiplied with the value of the "value 1" field.
If the result is greater than 10 the field is valid.<br><br>
<table border="0">
<tr>
<td>
<form name="testform" method="post" onSubmit="return validateStandard(this, "error");">
<table>
<tr>
<td class="mandatory">Value 1:</td>
<td><input type="text" name="value1" id="value1" required="1" regexp="/^\d*$/" size="40"></td>
<td class="comment">//--- Only digits allowed</td>
</tr>
<tr>
<td class="mandatory">Value 2:</td>
<td><input type="text" name="value2" id="value2" required="1" callback="validateValue2"></td>
<td class="comment">//--- field is valid if the value multiplied with the value 1 is greater than 10</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/jsval_1.3.4.zip">jsval_1.3.4.zip( 46 k)</a>
TextField input length validator
<HTML>
<HEAD>
<TITLE>jaxWidgets by Sarat Pediredla</TITLE>
<STYLE type=text/css>
BODY {
FONT-SIZE: 0.9em; FONT-FAMILY: Arial, serif
}
A {
TEXT-DECORATION: none
}
CODE {
CLEAR: both; DISPLAY: block; FONT-SIZE: 0.9em; FONT-FAMILY: "Courier New", arial, serif; BACKGROUND-COLOR: #00ffcc
}
highlight {
BACKGROUND-COLOR: #ffff99
}
.header {
PADDING-RIGHT: 15px; PADDING-LEFT: 10px; FONT-WEIGHT: normal; FONT-SIZE: 2.5em; PADDING-BOTTOM: 15px; MARGIN: 0px; PADDING-TOP: 1px; LETTER-SPACING: -0.05em
}
.header SPAN {
FONT-SIZE: 0.5em; FONT-FAMILY: Arial, serif; LETTER-SPACING: 0px
}
.toolheader {
MARGIN: 5px 10px; COLOR: #000000; BORDER-BOTTOM: #69c 2px solid; FONT-FAMILY: arial, serif
}
.layer {
CLEAR: both; BORDER-RIGHT: #ccc 1px solid; PADDING-RIGHT: 1em; BORDER-TOP: #ccc 1px solid; PADDING-LEFT: 1em; BACKGROUND: #fff; PADDING-BOTTOM: 0.5em; MARGIN: 15px 5%; OVERFLOW: auto; BORDER-LEFT: #ccc 1px solid; PADDING-TOP: 0.5em; BORDER-BOTTOM: #ccc 1px solid
}
.input {
BORDER-RIGHT: #ff0000 1px solid; BORDER-TOP: #ff0000 1px solid; OVERFLOW: auto; BORDER-LEFT: #ff0000 1px solid; BORDER-BOTTOM: #ff0000 1px solid
}
.button {
BORDER-RIGHT: #cccccc 1px ridge; PADDING-RIGHT: 2px; BORDER-TOP: #cccccc 1px ridge; PADDING-LEFT: 2px; PADDING-BOTTOM: 2px; BORDER-LEFT: #cccccc 1px ridge; PADDING-TOP: 2px; BORDER-BOTTOM: #cccccc 1px ridge; FONT-FAMILY: serif
}
.note {
FONT-SIZE: 0.8em
}
detailHeader {
FONT-WEIGHT: bold
}
detailContent {
CLEAR: left; DISPLAY: block
}
#mainmenu {
PADDING-RIGHT: 0.2em; PADDING-LEFT: 0.2em; BACKGROUND: #fff; PADDING-BOTTOM: 0.2em; MARGIN: 0px; PADDING-TOP: 0.2em; BORDER-BOTTOM: #707070 2px solid
}
#mainmenu A {
BORDER-RIGHT: #fff 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #fff 1px solid; PADDING-LEFT: 5px; FONT-WEIGHT: normal; FONT-SIZE: 16px; PADDING-BOTTOM: 3px; MARGIN: 0px; BORDER-LEFT: #fff 1px solid; COLOR: #333; PADDING-TOP: 3px; BORDER-BOTTOM: #fff 1px solid; TEXT-DECORATION: none
}
#mainmenu A:hover {
BORDER-RIGHT: #9d9d9d 1px solid; BORDER-TOP: #9d9d9d 1px solid; BACKGROUND: #ccc; BORDER-LEFT: #9d9d9d 1px solid; COLOR: #171717; BORDER-BOTTOM: #9d9d9d 1px solid
}
#mainmenu LI {
DISPLAY: inline; LINE-HEIGHT: 200%; LIST-STYLE-TYPE: none; TEXT-ALIGN: center
}
.testClass {
CLEAR: left; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: red; FONT-FAMILY: Arial, Helvetica, sans-serif
}
</style>
<!-- <LINK href="progressvalidator_files/jax.css" rel=stylesheet> -->
<!-- jaxWidgets_RuntimeEngine.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_RuntimeEngine.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The Runtime Engine to register and process widgets
=========================================
============= FEATURES ==================
- Dynamically loads and parses jaxWidgets
- i18n support for strings
============================================
============= FUTURE PLANS ==================
==============================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// Define namespace
if (typeof jaxWidgets != "object") { var jaxWidgets = {}; }
// Register namespace and object
jaxWidgets.RuntimeEngine = function()
{
var registeredWidgets = new Array();
var totalWidgets = -1;
var loadedWidgets = new Array();
var currentWidgets = new Array();
this.registerWidget = function(tag, handler)
{
var newWidget = new Array(tag, handler);
registeredWidgets[++totalWidgets] = newWidget;
};
this.loadEngine = function()
{
// Load library component
_Library = new jaxWidgets.Library();
for(var i=0; i <= totalWidgets; i++)
{
currentWidgets = document.getElementsByTagName("jax:"+registeredWidgets[i][0]);
for(var j =0; j < currentWidgets.length; j++)
{
registeredWidgets[i][1].load(currentWidgets[j]);
}
_Library.cleanup(currentWidgets);
}
};
/*
Debug function for testing purposes only
You NEED to create a div with id=debug in your page for this to work
*/
this.writeDebug = function(string)
{
document.getElementById("debug").innerHTML += string + "<br>";
};
/*
Error Log function. Can be disabled through setErrors(false)
*/
this.writeError = function(string)
{
if(document.getElementById("jaxErrorLogDiv"))
{
document.getElementById("jaxErrorLogDiv").innerHTML += string + "<br>";
}
else
{
var logDiv = document.createElement("div");
logDiv.setAttribute("id","jaxErrorLogDiv");
logDiv.style.color = "red";
logDiv.style.fontSize = "0.9em";
logDiv.style.fontWeight = "bold";
var bodyTag = document.getElementsByTagName("body")[0];
bodyTag.insertBefore(logDiv,bodyTag.firstChild);
logDiv.innerHTML = "jax Error : ";
logDiv.innerHTML += string + "<br>";
}
};
}
// Register event handlers
// Use quirksmode idea for flexible registration by copying existing events
// onKeyUp
/******* Define GLOBAL Constants *********/
var _Engine; // The jax Runtime Engine
var _Library; // The jax Runtime library
_Engine = new jaxWidgets.RuntimeEngine();
var oldEventCode = (window.onload) ? elm.onload : function () {};
window.onload = function () {oldEventCode(); _Engine.loadEngine();};
</SCRIPT>
<!-- jaxWidgets_Library.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_Library.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The Library is a repository for common functions used by jaxWidgets
=========================================
============= FEATURES ==================
- Sets Style of elements
============================================
============= CHANGELOG ==================
17 June 2005 [17:46] [Sarat Pediredla]
- Modified code to replace getAttribute().toLowerCase() with tmpString
because strangely IE 6.0 wont support it.
18 June 2005 [08:45] [Sarat Pediredla]
- Added functions to get X & Y position of elements.
- Modified style setters to use element.style.cssText
==========================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// The following array IS NEEDED for widgets wishing to lock submitting forms
var submitLockedBy = new Array();
// Register object
jaxWidgets.Library = function()
{
// Cleanup function to remove jax XML tags
this.cleanup = function(array)
{
var arraylength = array.length;
for(var i=0; i < arraylength; i++)
{
var element = array[0];
element.parentNode.removeChild(element);
}
return true;
}
// Gets the index of an element in an array
this.getIndex = function(element,array)
{
for(var i=0; i < array.length; i++)
{
if(array[i] == element)
return i;
}
}
// Sets the CSS style from source to target element
this.setStyle = function(sourceElement,targetElement)
{
if(sourceElement.getAttribute("style") && sourceElement.getAttribute("style").length > 0)
{
targetElement.style.cssText = sourceElement.getAttribute("style");
return;
}
if(sourceElement.getAttribute("class") && sourceElement.getAttribute("class").length > 0)
{
targetElement.setAttribute("className",sourceElement.getAttribute("class"));
targetElement.setAttribute("class",sourceElement.getAttribute("class"));
return;
}
}
// Returns parent form of a given element
this.getParentForm = function(element)
{
for(var i=0;i < document.forms.length; i++)
{
if(document.forms[i][element.id] == element)
return document.forms[i];
}
_Engine.writeError("jax Error : Your elements are not embedded inside a form");
return null;
}
// Returns the submit button for a given form
this.getSubmitElement = function(currentForm)
{
for(i=0;i<currentForm.length;i++)
{
var currentElement = currentForm.elements[i];
var tmpString = currentElement.type;
if(tmpString.toString().toLowerCase() == "submit")
return currentElement;
}
}
// Disables submitting of forms when fields not validated
this.disableSubmit = function(element)
{
form = this.getParentForm(element);
var btnSubmit = this.getSubmitElement(form);
if(btnSubmit)
btnSubmit.disabled = true;
}
this.enableSubmit = function(element)
{
form = this.getParentForm(element);
var btnSubmit = this.getSubmitElement(form);
if(btnSubmit)
btnSubmit.disabled = false;
}
this.lockSubmit = function(id)
{
var index = _Library.getIndex(id,submitLockedBy)
if(!(index >= 0))
{
submitLockedBy.push(id);
}
_Library.disableSubmit(document.getElementById(id));
}
this.unlockSubmit = function(id)
{
var index = _Library.getIndex(id, submitLockedBy);
if(index > -1)
{
submitLockedBy.pop(index);
if(_Library.noSubmitLocks())
_Library.enableSubmit(document.getElementById(id));
}
}
this.noSubmitLocks = function()
{
if(submitLockedBy.length <= 0)
return true;
return false;
}
this.getXPos = function(element)
{
xPos = element.offsetLeft;
tempEl = element.offsetParent;
while (tempEl != null)
{
xPos += (tempEl.offsetLeft);
tempEl = tempEl.offsetParent;
}
return xPos;
}
this.getYPos = function(element)
{
yPos = element.offsetTop;
tempEl = element.offsetParent;
while (tempEl != null)
{
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
}
</SCRIPT>
<!-- jaxWidgets_ProgressValidator.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_ProgressValidator.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 15/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The progress validator widget is a part of the jaxWidgets library. It provides an
interactive progress bar below text fields allowing you to limit characters.
This is used best in textareas where the progess
=========================================
============= FEATURES ==================
- Uses jaxXML markup tags to specify designer friendly tags in HTML (.NET style)
- i18n support for strings
- Customisable UI
- Use on any number of fields
- Supports both Bar and Text type progress fields.
============================================
============= CHANGELOG ==================
17 June 2005 [17:46]
- Modified code to replace getAttribute().toLowerCase() with tmpString
because strangely IE 6.0 wont support it.
==========================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
jaxWidgets.ProgressValidator = function()
{
// Validation settings
maxLength = 20; // Defines maximum length of field
minLength = 0; // Defines minimum length of field
isRequired = false; // Is field required?
// i18n settings
strRequired = "Required";
strRemaining = "characters remaining";
strLimit = "Left : ";
// UI settings
strType = "TEXT"; // Field display type enum{BAR,TEXT}
BackColor = "#0000FF";
TextColor = "#FFFFFF";
BorderColor = "#000000";
FontSize = "0.7em";
FontFamily = "Verdana, Arial, serif";
var tmpString;
// Plugin interface to load element
this.load = function(element)
{
if(!element)
{
_Engine.writeError("jax Error: Progress Field Validator cannot load");
return;
}
var countElement = document.getElementById(element.getAttribute("ControlToValidate"));
if(!countElement)
{
_Engine.writeError("jax Error: Progress validator is missing a ControlToValidate attribute");
return;
}
var progressElement;
// Determine if we need a BAR or TEXT progress displayed
var tmpType = element.getAttribute("Type");
if(tmpType == "BAR")
{
progressElement = this.createBarProgress(element,countElement);
}
else
{
progressElement = this.createTextProgress(element,countElement);
}
// Standrad function to parse the custom jax tag
this.parseTag(element,progressElement);
// Create style
_Library.setStyle(element,progressElement);
tmpString = progressElement.getAttribute("isRequired");
if(tmpString.toString().toLowerCase() == "true")
{
_ProgressValidator.validate(countElement.id);
}
// Register event handlers
var oldEventCode = (countElement.onkeyup) ? countElement.onkeyup : function () {};
countElement.onkeyup = function () {oldEventCode(); _ProgressValidator.validate(countElement.id)};
}
// Create a text progress layer
this.createTextProgress = function(element, countElement)
{
var progressElement = document.createElement("div");
progressElement.setAttribute("id",countElement.id+"_prgvalid");
element.parentNode.insertBefore(progressElement,element.nextSibling);
return progressElement;
}
// Create a bar progress layer
this.createBarProgress = function(element,countElement)
{
var progressElement = document.createElement("div");
progressElement.setAttribute("id",countElement.id+"_prgvalid");
progressElement.setAttribute("width","0px");
progressElement.setAttribute("maxWidth",countElement.offsetWidth);
progressElement.style.color = TextColor;
progressElement.style.backgroundColor = BackColor;
progressElement.style.overflow = "hidden";
progressElement.style.height = "15px";
progressElement.style.fontSize = FontSize;
progressElement.style.fontFamily = FontFamily;
progressElement.style.fontWeight = "bold";
progressElement.style.display = "block";
countElement.parentNode.insertBefore(progressElement,countElement.nextSibling);
return progressElement;
}
this.validate = function(id)
{
var element;
if(!(element=document.getElementById(id)))
{
return false;
}
var progressDiv = document.getElementById(id+"_prgvalid");
switch(progressDiv.getAttribute("strtype"))
{
case "BAR" : this.validateBar(element, progressDiv);
break;
case "TEXT" : this.validateText(element, progressDiv);
break;
}
return true;
}
this.parseTag = function(element, progressElement)
{
if(element.getAttribute("MaxLength"))
progressElement.setAttribute("maxLength",element.getAttribute("MaxLength"));
else
progressElement.setAttribute("maxLength",maxLength);
if(element.getAttribute("MinLength"))
progressElement.setAttribute("MinLength",element.getAttribute("MinLength"));
else
progressElement.setAttribute("MinLength",minLength);
if(element.getAttribute("Required"))
progressElement.setAttribute("isRequired",element.getAttribute("Required"));
else
progressElement.setAttribute("isRequired",isRequired);
if(element.getAttribute("TextRequired"))
progressElement.setAttribute("strRequired",element.getAttribute("TextRequired"));
else
progressElement.setAttribute("strRequired",strRequired);
if(element.getAttribute("TextRemaining"))
progressElement.setAttribute("strRemaining",element.getAttribute("TextRemaining"));
else
progressElement.setAttribute("strRemaining",strRemaining);
if(element.getAttribute("TextLimit"))
progressElement.setAttribute("strLimit",element.getAttribute("TextLimit"));
else
progressElement.setAttribute("strLimit",strLimit);
if(element.getAttribute("Type"))
progressElement.setAttribute("strType",element.getAttribute("Type"));
else
progressElement.setAttribute("strType",strType);
}
this.validateText = function(element, progressDiv)
{
// Reset display
if(progressDiv.getAttribute("isRequired") == "true")
{
if(element.value.length <= 0)
{
_Library.lockSubmit(element.id);
progressDiv.innerHTML = progressDiv.getAttribute("strRequired");
return false;
}
}
if((progressDiv.getAttribute("maxLength") - element.value.length) < 0)
{
element.value = element.value.substring(0, progressDiv.getAttribute("maxLength"));
return false;
}
progressDiv.innerHTML = "<strong>"+(progressDiv.getAttribute("maxLength") - element.value.length)+"</strong> "+progressDiv.getAttribute("strRemaining");
_Library.unlockSubmit(element.id);
}
this.validateBar = function(element, progressDiv)
{
var progressUnit = progressDiv.getAttribute("maxWidth") / progressDiv.getAttribute("maxLength");
var barSize = element.value.length * progressUnit;
var progressPercent = parseInt(((progressDiv.getAttribute("maxWidth") - barSize) / progressDiv.getAttribute("maxWidth")) * 100);
// Reset display
if(progressDiv.getAttribute("isRequired") == "true")
{
if(element.value.length <= 0)
{
_Library.lockSubmit(element.id);
progressDiv.innerHTML = progressDiv.getAttribute("strRequired");
progressDiv.style.width = progressDiv.getAttribute("maxWidth")+"px";
return false;
}
}
if((progressDiv.getAttribute("maxLength") - element.value.length) < 0)
{
element.value = element.value.substring(0, progressDiv.getAttribute("maxLength"));
return false;
}
progressDiv.style.width = barSize+"px";
progressDiv.innerHTML = progressDiv.getAttribute("strLimit")+progressPercent + "%";
_Library.unlockSubmit(element.id);
}
this.registerWithEngine = function(_ProgressValidator)
{
var tag = "ProgressValidator";
var handler = _ProgressValidator;
_Engine.registerWidget(tag, handler);
}
}
var _ProgressValidator = new jaxWidgets.ProgressValidator()
_ProgressValidator.registerWithEngine(_ProgressValidator);
</SCRIPT>
<BODY>
<H2>Demo </H2></DIV>
<DIV class=layer id=jaxDetail>This is a TEXT ProgressValidator <BR><BR>
<CENTER>
<FORM id=testForm><INPUT id=test1> <JAX:PROGRESSVALIDATOR MaxLength="10"
Required="true"
ControlToValidate="test1"></JAX:PROGRESSVALIDATOR><BR></FORM></CENTER>
This is a BAR
ProgressValidator <BR><BR>
<FORM id=testForm2><TEXTAREA id=test2 rows=5 cols=45></TEXTAREA>
<JAX:PROGRESSVALIDATOR MaxLength="30" Required="true"
ControlToValidate="test2" Type="BAR"
TextRequired="Wanted"></JAX:PROGRESSVALIDATOR><BR></FORM>
<P><STRONG>Code :</STRONG> <BR></BODY></HTML>
TextField validator: email, IP address and URL
<HTML>
<HEAD>
<TITLE>jaxWidgets by Sarat Pediredla</TITLE>
<STYLE type=text/css>
BODY {
FONT-SIZE: 0.9em; FONT-FAMILY: Arial, serif
}
A {
TEXT-DECORATION: none
}
CODE {
CLEAR: both; DISPLAY: block; FONT-SIZE: 0.9em; FONT-FAMILY: "Courier New", arial, serif; BACKGROUND-COLOR: #00ffcc
}
highlight {
BACKGROUND-COLOR: #ffff99
}
.header {
PADDING-RIGHT: 15px; PADDING-LEFT: 10px; FONT-WEIGHT: normal; FONT-SIZE: 2.5em; PADDING-BOTTOM: 15px; MARGIN: 0px; PADDING-TOP: 1px; LETTER-SPACING: -0.05em
}
.header SPAN {
FONT-SIZE: 0.5em; FONT-FAMILY: Arial, serif; LETTER-SPACING: 0px
}
.toolheader {
MARGIN: 5px 10px; COLOR: #000000; BORDER-BOTTOM: #69c 2px solid; FONT-FAMILY: arial, serif
}
.layer {
CLEAR: both; BORDER-RIGHT: #ccc 1px solid; PADDING-RIGHT: 1em; BORDER-TOP: #ccc 1px solid; PADDING-LEFT: 1em; BACKGROUND: #fff; PADDING-BOTTOM: 0.5em; MARGIN: 15px 5%; OVERFLOW: auto; BORDER-LEFT: #ccc 1px solid; PADDING-TOP: 0.5em; BORDER-BOTTOM: #ccc 1px solid
}
.input {
BORDER-RIGHT: #ff0000 1px solid; BORDER-TOP: #ff0000 1px solid; OVERFLOW: auto; BORDER-LEFT: #ff0000 1px solid; BORDER-BOTTOM: #ff0000 1px solid
}
.button {
BORDER-RIGHT: #cccccc 1px ridge; PADDING-RIGHT: 2px; BORDER-TOP: #cccccc 1px ridge; PADDING-LEFT: 2px; PADDING-BOTTOM: 2px; BORDER-LEFT: #cccccc 1px ridge; PADDING-TOP: 2px; BORDER-BOTTOM: #cccccc 1px ridge; FONT-FAMILY: serif
}
.note {
FONT-SIZE: 0.8em
}
detailHeader {
FONT-WEIGHT: bold
}
detailContent {
CLEAR: left; DISPLAY: block
}
#mainmenu {
PADDING-RIGHT: 0.2em; PADDING-LEFT: 0.2em; BACKGROUND: #fff; PADDING-BOTTOM: 0.2em; MARGIN: 0px; PADDING-TOP: 0.2em; BORDER-BOTTOM: #707070 2px solid
}
#mainmenu A {
BORDER-RIGHT: #fff 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #fff 1px solid; PADDING-LEFT: 5px; FONT-WEIGHT: normal; FONT-SIZE: 16px; PADDING-BOTTOM: 3px; MARGIN: 0px; BORDER-LEFT: #fff 1px solid; COLOR: #333; PADDING-TOP: 3px; BORDER-BOTTOM: #fff 1px solid; TEXT-DECORATION: none
}
#mainmenu A:hover {
BORDER-RIGHT: #9d9d9d 1px solid; BORDER-TOP: #9d9d9d 1px solid; BACKGROUND: #ccc; BORDER-LEFT: #9d9d9d 1px solid; COLOR: #171717; BORDER-BOTTOM: #9d9d9d 1px solid
}
#mainmenu LI {
DISPLAY: inline; LINE-HEIGHT: 200%; LIST-STYLE-TYPE: none; TEXT-ALIGN: center
}
.testClass {
CLEAR: left; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: red; FONT-FAMILY: Arial, Helvetica, sans-serif
}
</STYLE>
<!-- jaxWidgets_RuntimeEngine.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_RuntimeEngine.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The Runtime Engine to register and process widgets
=========================================
============= FEATURES ==================
- Dynamically loads and parses jaxWidgets
- i18n support for strings
============================================
============= FUTURE PLANS ==================
==============================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// Define namespace
if (typeof jaxWidgets != "object") { var jaxWidgets = {}; }
// Register namespace and object
jaxWidgets.RuntimeEngine = function()
{
var registeredWidgets = new Array();
var totalWidgets = -1;
var loadedWidgets = new Array();
var currentWidgets = new Array();
this.registerWidget = function(tag, handler)
{
var newWidget = new Array(tag, handler);
registeredWidgets[++totalWidgets] = newWidget;
};
this.loadEngine = function()
{
// Load library component
_Library = new jaxWidgets.Library();
for(var i=0; i <= totalWidgets; i++)
{
currentWidgets = document.getElementsByTagName("jax:"+registeredWidgets[i][0]);
for(var j =0; j < currentWidgets.length; j++)
{
registeredWidgets[i][1].load(currentWidgets[j]);
}
_Library.cleanup(currentWidgets);
}
};
/*
Debug function for testing purposes only
You NEED to create a div with id=debug in your page for this to work
*/
this.writeDebug = function(string)
{
document.getElementById("debug").innerHTML += string + "<br>";
};
/*
Error Log function. Can be disabled through setErrors(false)
*/
this.writeError = function(string)
{
if(document.getElementById("jaxErrorLogDiv"))
{
document.getElementById("jaxErrorLogDiv").innerHTML += string + "<br>";
}
else
{
var logDiv = document.createElement("div");
logDiv.setAttribute("id","jaxErrorLogDiv");
logDiv.style.color = "red";
logDiv.style.fontSize = "0.9em";
logDiv.style.fontWeight = "bold";
var bodyTag = document.getElementsByTagName("body")[0];
bodyTag.insertBefore(logDiv,bodyTag.firstChild);
logDiv.innerHTML = "jax Error : ";
logDiv.innerHTML += string + "<br>";
}
};
}
// Register event handlers
// Use quirksmode idea for flexible registration by copying existing events
// onKeyUp
/******* Define GLOBAL Constants *********/
var _Engine; // The jax Runtime Engine
var _Library; // The jax Runtime library
_Engine = new jaxWidgets.RuntimeEngine();
var oldEventCode = (window.onload) ? elm.onload : function () {};
window.onload = function () {oldEventCode(); _Engine.loadEngine();};
</SCRIPT>
<!-- jaxWidgets_Library.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_Library.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The Library is a repository for common functions used by jaxWidgets
=========================================
============= FEATURES ==================
- Sets Style of elements
============================================
============= CHANGELOG ==================
17 June 2005 [17:46] [Sarat Pediredla]
- Modified code to replace getAttribute().toLowerCase() with tmpString
because strangely IE 6.0 wont support it.
18 June 2005 [08:45] [Sarat Pediredla]
- Added functions to get X & Y position of elements.
- Modified style setters to use element.style.cssText
==========================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// The following array IS NEEDED for widgets wishing to lock submitting forms
var submitLockedBy = new Array();
// Register object
jaxWidgets.Library = function()
{
// Cleanup function to remove jax XML tags
this.cleanup = function(array)
{
var arraylength = array.length;
for(var i=0; i < arraylength; i++)
{
var element = array[0];
element.parentNode.removeChild(element);
}
return true;
}
// Gets the index of an element in an array
this.getIndex = function(element,array)
{
for(var i=0; i < array.length; i++)
{
if(array[i] == element)
return i;
}
}
// Sets the CSS style from source to target element
this.setStyle = function(sourceElement,targetElement)
{
if(sourceElement.getAttribute("style") && sourceElement.getAttribute("style").length > 0)
{
targetElement.style.cssText = sourceElement.getAttribute("style");
return;
}
if(sourceElement.getAttribute("class") && sourceElement.getAttribute("class").length > 0)
{
targetElement.setAttribute("className",sourceElement.getAttribute("class"));
targetElement.setAttribute("class",sourceElement.getAttribute("class"));
return;
}
}
// Returns parent form of a given element
this.getParentForm = function(element)
{
for(var i=0;i < document.forms.length; i++)
{
if(document.forms[i][element.id] == element)
return document.forms[i];
}
_Engine.writeError("jax Error : Your elements are not embedded inside a form");
return null;
}
// Returns the submit button for a given form
this.getSubmitElement = function(currentForm)
{
for(i=0;i<currentForm.length;i++)
{
var currentElement = currentForm.elements[i];
var tmpString = currentElement.type;
if(tmpString.toString().toLowerCase() == "submit")
return currentElement;
}
}
// Disables submitting of forms when fields not validated
this.disableSubmit = function(element)
{
form = this.getParentForm(element);
var btnSubmit = this.getSubmitElement(form);
if(btnSubmit)
btnSubmit.disabled = true;
}
this.enableSubmit = function(element)
{
form = this.getParentForm(element);
var btnSubmit = this.getSubmitElement(form);
if(btnSubmit)
btnSubmit.disabled = false;
}
this.lockSubmit = function(id)
{
var index = _Library.getIndex(id,submitLockedBy)
if(!(index >= 0))
{
submitLockedBy.push(id);
}
_Library.disableSubmit(document.getElementById(id));
}
this.unlockSubmit = function(id)
{
var index = _Library.getIndex(id, submitLockedBy);
if(index > -1)
{
submitLockedBy.pop(index);
if(_Library.noSubmitLocks())
_Library.enableSubmit(document.getElementById(id));
}
}
this.noSubmitLocks = function()
{
if(submitLockedBy.length <= 0)
return true;
return false;
}
this.getXPos = function(element)
{
xPos = element.offsetLeft;
tempEl = element.offsetParent;
while (tempEl != null)
{
xPos += (tempEl.offsetLeft);
tempEl = tempEl.offsetParent;
}
return xPos;
}
this.getYPos = function(element)
{
yPos = element.offsetTop;
tempEl = element.offsetParent;
while (tempEl != null)
{
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
return yPos;
}
}
</SCRIPT>
<!-- jaxWidgets_Validator.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_Validator.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 27/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The validator widget is a part of the jaxWidgets library. It provides
dynamic in-page validation of common fields.
=========================================
============= FEATURES ==================
- Uses jaxXML markup tags to specify designer friendly tags in HTML (.NET style)
- i18n support for strings
- Customisable UI
- Use on any number of fields
- Validates most common formats
============================================
============= CHANGELOG ==================
==========================================
LICENSE: LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// Register object
jaxWidgets.Validator = function()
{
// Validation settings
var isRequired = "false";
// Common regexs
var regexEmail = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
var regexUrl = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
var regexDate = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
var regexTime = /^([1-9]|1[0-2]):[0-5]\d$/;
var regexIP = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var regexInteger = /(^-?\d\d*$)/;
// United states specific regexs
var regexPostcode_US = /\d{5}(-\d{4})?/;
var regexSSN_US = /\d{3}-\d{2}-\d{4}/;
var regexPhone_US = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
var regexState_US = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;
// United Kingdom specific regexs
var regexPostcode_UK = /^([A-Za-z]{1,2})([0-9]{2,3})([A-Za-z]{2})$/;
// i18n settings
var strLocale = "US";
var strType = "String";
var strRequired = "Required";
var strInvalid = "Invalid format";
// Internal global vars
var tmpString;
// Create validator
this.load = function(element)
{
if(!element)
{
_Engine.writeError("jax Error: Validator cannot load");
return;
}
var fieldElement = document.getElementById(element.getAttribute("ControlToValidate"));
if(!fieldElement)
{
_Engine.writeError("jax Error: Validator is missing a ControlToValidate attribute");
return;
}
// Create validator layer
var validatorElement = document.createElement("span");
validatorElement.setAttribute("id",fieldElement.id+"_valid");
element.parentNode.insertBefore(validatorElement,element.nextSibling);
// Standard function to parse the custom jax tag
this.parseTag(element,validatorElement);
// Create style for current element using DOM compatible function from Library
_Library.setStyle(element, validatorElement);
tmpString = validatorElement.getAttribute("isRequired")
if(tmpString.toString().toLowerCase() == "true")
{
_Validator.validate(fieldElement.id);
}
// Register event handlers
// Use quirksmode idea for flexible registration by copying existing events
// onSubmit
var parentForm = _Library.getParentForm(fieldElement);
var oldEventCode = (parentForm.onsubmit) ? parentForm.onsubmit : function () {};
parentForm.onsubmit = function () {oldEventCode(); return _Validator.validate(fieldElement.id)};
// onBlue
var oldEventCode = (fieldElement.onblur) ? fieldElement.onblur : function () {};
fieldElement.onblur = function () {oldEventCode(); return _Validator.validate(fieldElement.id)};
};
this.setInvalid = function(div)
{
div.innerHTML = div.getAttribute("strInvalid");
};
this.validate = function(id)
{
var element;
if(!(element = document.getElementById(id)))
{
return false;
}
var validDiv = document.getElementById(id+"_valid");
var validString = element.value;
if(validString.length == 0)
{
tmpString = validDiv.getAttribute("isRequired");
var isRequired = tmpString.toString().toLowerCase();
if(isRequired == "true")
{
validDiv.innerHTML = validDiv.getAttribute("strRequired");
return false;
}
else
{
validDiv.innerHTML = "";
}
}
// If we have reached here, we can continue with validation
var tmpLocale = validDiv.getAttribute("strLocale");
switch(validDiv.getAttribute("strType"))
{
case "String" :
return true;
break;
case "Email" :
if(!validString.match(regexEmail))
{ this.setInvalid(validDiv); return false; }
break;
case "Url" :
if(!validString.match(regexUrl))
{ this.setInvalid(validDiv); return false; }
break;
case "Date" :
if(!validString.match(regexDate))
{ this.setInvalid(validDiv); return false; }
break;
case "Time" :
if(!validString.match(regexTime))
{ this.setInvalid(validDiv); return false; }
break;
case "IP" :
if(!validString.match(regexIP))
{ this.setInvalid(validDiv); return false; }
break;
case "Integer" :
if(!validString.match(regexInteger))
{ this.setInvalid(validDiv); return false; }
break;
case "Postcode" :
switch(tmpLocale)
{
case "US" :
if(!validString.match(regexPostcode_US))
{ this.setInvalid(validDiv); return false; }
break;
case "Email" :
if(!validString.match(regexPostcode_UK))
{ this.setInvalid(validDiv); return false; }
break;
}
break;
// No need to check locale for SSN as it is US specific
case "SSN" :
if(!validString.match(regexSSN_US))
{ this.setInvalid(validDiv); return false; }
break;
case "Phone" :
switch(tmpLocale)
{
case "US" :
if(!validString.match(regexPhone_US))
{ this.setInvalid(validDiv); return false; }
break;
}
break;
// Only US States work for now
case "State" :
switch(tmpLocale)
{
case "Email" :
if(!validString.match(regexState_US))
{ this.setInvalid(validDiv); return false; }
break;
}
break;
// Do custom validation
case "Custom" :
if(!validString.match(validDiv.getAttribute("Match")))
{ this.setInvalid(validDiv); return false; }
break;
}
// If we have reached here, everything is OK
validDiv.innerHTML = "";
return true;
};
/********* Custom tag parser **********/
this.parseTag = function(element,validatorElement)
{
if(element.getAttribute("Required"))
validatorElement.setAttribute("isRequired",element.getAttribute("Required"));
else
validatorElement.setAttribute("isRequired",isRequired);
if(element.getAttribute("TextRequired"))
validatorElement.setAttribute("strRequired",element.getAttribute("TextRequired"));
else
validatorElement.setAttribute("strRequired",strRequired);
if(element.getAttribute("TextInvalid"))
validatorElement.setAttribute("strInvalid",element.getAttribute("TextInvalid"));
else
validatorElement.setAttribute("strInvalid",strInvalid);
if(element.getAttribute("Type"))
validatorElement.setAttribute("strType", element.getAttribute("Type"));
else
validatorElement.setAttribute("strType", strType);
if(element.getAttribute("Locale"))
validatorElement.setAttribute("strLocale", element.getAttribute("Locale"));
else
validatorElement.setAttribute("strLocale", strLocale);
if(element.getAttribute("Match"))
validatorElement.setAttribute("strCustom", element.getAttribute("Match"));1
};
this.registerWithEngine = function(_Validator)
{
var tag = "Validator";
var handler = _Validator;
_Engine.registerWidget(tag, handler);
};
}
var _Validator = new jaxWidgets.Validator();
_Validator.registerWithEngine(_Validator);
</SCRIPT>
<BODY>
<H2>Demo</H2>
<DIV class=layer id=jaxDetail>This is a demo for jax Validators <BR><BR>
<FORM id=testForm name=form method=post>IP Address :
<INPUT id=ip>
<JAX:VALIDATOR class=testClass Required="true" Type="IP" ControlToValidate="ip">
</JAX:VALIDATOR>
<BR>Email:
<INPUT id=email>
<JAX:VALIDATOR class=testClass Required="true" Type="Email" ControlToValidate="email" TextRequired="Cant be empty">
</JAX:VALIDATOR>
<BR>URL :
<INPUT id=url>
<JAX:VALIDATOR class=testClass Type="Url" ControlToValidate="url" TextInvalid="Need website">
</JAX:VALIDATOR>
<BR>
<INPUT id=submitbtn type=submit value=submit>
</FORM>
</BODY>
</HTML>
Validate an field with a maximum number of characters
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
</script>
</head>
<body>
<form name="myForm" action="http://www.wbex.ru" onsubmit="return validate()">
Enter some text (less than 5 characters):
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>
</html>
Validate an input field with minimum and maximum values
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
txt=x.myInput.value
if (txt>=1 && txt<=5) {
return true
}else{
alert("Must be between 1 and 5")
return false
}
}
</script>
</head>
<body>
<form name="myForm" action="http://www.wbex.ru" onsubmit="return validate()">
Enter a value from 1 to 5:
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>
</html>
Validate a number
function processNumber(inputField) {
try {
var inpVal = parseInt(inputField.value, 10);
if (isNaN(inpVal)) {
var msg = "Please enter a number only.";
var err = new Error(msg);
if (!err.message) {
err.message = msg;
}
throw err;
}
} catch (e) {
alert(e.message);
inputField.focus();
inputField.select();
}
}
Validate email address
function isEMailAddr(elem) {
var str = elem.value;
var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!str.match(re)) {
alert("Verify the e-mail address format.");
setTimeout("focusElement("" + elem.form.name + "", "" + elem.name + "")", 0);
return false;
} else {
return true;
}
}
Validating User Input
<html>
<head>
<title>Form validation</title>
<script language="JavaScript">
<!-- script start
function validateComplete(formObj) {
if (emptyField(formObj.firstName))
alert("Please enter your first name.");
else if (emptyField(formObj.lastName))
alert("Please enter your last name.");
else if (emptyField(formObj.address1)
&& emptyField(formObj.address2))
alert("Please enter your address.");
else if (emptyField(formObj.city))
alert("Please enter your city or town.");
else if (emptyField(formObj.state))
alert("Please enter your state.");
else if (emptyField(formObj.email))
alert("Please enter your E-mail address.");
else return true;
return false;
}
// Check to see if field is empty
function emptyField(textObj)
{
if (textObj.value.length == 0) return true;
for (var i=0; i<textObj.value.length; ++i) {
var ch = textObj.value.charAt(i);
if (ch != " " && ch != "\t") return false;
}
return true;
}
// script end -->
</script>
</head>
<body>
<h1>form validation</h1>
<form name="myform" action="actionURL" method="post" onSubmit="return validateComplete(document.myform)">
<pre>
First Name:<input type="text" name="firstName">
Last Name: <input type="text" name="lastName">
Address: <input type="text" name="address1">
<input type="text" name="address2">
</pre>
City/Town:
<input type="text" name="city" size=12>
State:
<input type="text" name="state" size=2>
Zip Code:
<input type="text" name="zip" size=5>
<pre>
Home Phone:<input type="text" name="homePhone" size=12>
Work Phone:<input type="text" name="workPhone" size=12>
FAX: <input type="text" name="FAX" size=12>
E-mail Address: <input type="text" name="email">
Quest: <input type="text" name="quest">
Favorite Color: <input type="text" name="favColor">
</pre>
<hr>
<input type="submit" name="submit" value="Submit">
</form>
<body>
<html>