A CSS is used to highlight the fields which failed to validate : Validation « Form Control « JavaScript DHTML

JavaScript DHTML
1. Ajax Layer
2. Data Type
3. Date Time
4. Development
5. Document
6. Dojo toolkit
7. Event
8. Event onMethod
9. Ext JS
10. Form Control
11. GUI Components
12. HTML
13. Javascript Collections
14. Javascript Objects
15. Javascript Properties
16. jQuery
17. Language Basics
18. Mochkit
19. Mootools
20. Node Operation
21. Object Oriented
22. Page Components
23. Rico
24. Scriptaculous
25. Security
26. SmartClient
27. Style Layout
28. Table
29. Utilities
30. Window Browser
31. YUI Library
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
JavaScript DHTML » Form Control » Validation 
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; }
.comment    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>&nbsp;</td>
                        <td><input type="submit" value="Submit"></td>
                    </tr>
                </table>
                </form>

            </td>
        </tr>
    </table>
</body>
</html>

           
       
jsval_1.3.4.zip( 46 k)
Related examples in the same category
1. Form validation: Not Empty, Valid Radio, is Number, string length, EMail Address
2. Validate an input field with minimum and maximum values
3. Validate an field with a maximum number of characters
4. Phone Number Validation
5. Creating Reusable Validation Code
6. Credit Card Validation
7. Money Format
8. Validating User Input
9. Validate email address
10. Validate a number
11. TextField input length validator
12. Password field validator
13. TextField validator: email, IP address and URL
14. Must be at least 3 characters and not more than 8
15. Only characters are allowed
16. Can be empty
17. Must be a valid email address
18. ComboBox(list box): Must be selected one
19. InputBox: value must be between 10 and 90
20. Not stop when the first failed validation is encountered
21. Need to select a file
22. A simple form with two passwords that must have the same value
23. Shows the usage of callback functions for checking a field
24. Javascript validation framework
25. Form validator library
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.