/    Sign up×
Community /Pin to ProfileBookmark

Hi,

I have a form and in which fields are dynamically created and I am using javascript to validate the form and if the validation fails it shows the error message using alert(‘message’);

what i want to do is I want to display the error message in the form of a text message rather than alert.

For time being I have hard coded a dummy code like this

[code]
<?xml version=”1.0″ encoding=”iso-8859-1″ ?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>Webcredible – JavaScript tutorial – form validation</title>
<style type=”text/css”>@import “css.css”;</style>
<script type=”text/javascript” src=”form.js”></script>
</head>
<body>

<h1>Using Javascript to validate forms</h1>
<p>This page demonstrates how JavaScript can be used to validate a form.</p>
<div id=”form”>
<form action=”” name = “form1” onsubmit = “return validate_form(this);”>
<fieldset>
<legend>Article feedback</legend>

<ul>

<li><label for=”question” >Did you find this article useful? <img src=”req.gif” alt=”Required” /></label><input class=”mandatory” id=”question” value=”” /></li>
<input class=”mandatory” id=”question” value=”” type=”checkbox” name=”check” >Apple
<input class = “check” id = “question” value=”” type=”checkbox” name=”check”>Orange
<input class = “mandatory|email” id = “question” value=”” type=”text”>Email
<input type=”radio” class=’mandatory’ value=””>Computer
<input type =”radio” class=” ” value=””>Laptop
<select class=”mandatory” id=”question”name = “drop” type=”select”>
<option value=””>–Select–</option>
<option value=”gun”>Gun</option>
<option value=”riffle”>Riffle</option>
<option value=”pistol”>Pistol</option>
</select>

<select class=”” id=”question”name = “drop”>
<option value=””>–Select–</option>
<option value=”gun”>Bomb</option>
<option value=”riffle”>Pirangi</option>
<option value=”pistol”>Vanam</option>
</select>

<textarea rows=”20″ cols=”30″ class=”mandatory” id=”form1″ name=”text2″></textarea>
<textarea rows=”20″ cols=”30″ class=”mandatory” id=”form1″ name=”text3″></textarea>

</ul>
</fieldset>
<p>Thank you for taking the time to comple this form.</p>
<p><input type=”submit” class=”button” value=”Submit form” /></p>
</form>
</div>
</body>
</html>[/code]

But the class name for the fields would be either null, or mandatory or mandatory|email or mandatory|number etc accordingly…. Based on these classname alerts error messages

Now the JS code for this would be

[code]
var form
function validate_form(formname)
{
var input_tags = document.getElementsByTagName(“input”);
var textarea_tags=document.getElementsByTagName(“textarea”);
var dropdown_tags=document.getElementsByTagName(“select”);
var form_elements = concat_collection(input_tags,textarea_tags,dropdown_tags);
for (var i=0;i<form_elements.length;i++)
{
var classname = form_elements[i].className;
var splitelements = classname.split(“|”);

if(splitelements.length == 2)
{

//check for mandatory field, if empty return false here
//if value not empty, pass the splitelements[0] to validation function

return_value = required(form_elements[i]);

if (return_value == false)
{
return false;
}
else
{

return_value= validation(splitelements[1],form_elements[i]);

if(return_value==false)
{
return false;
}

}

//return validation(tagelements[i]);
}
if(splitelements.length == 1)
{
// check splitelement == required or not
if(splitelements==”mandatory”)
{

ret_val = required(form_elements[i]);
if (ret_val == false)
{
return false;
}

}

else if(form_elements[i].value!=””)
{

return_value= validation(splitelements[1],form_elements[i]);
if(return_value==false)
{
return false;
}
}

}

}//for loop

return true;
}//function

function required(reqtagelements)

{

if(reqtagelements.type==”text”)
{
if (reqtagelements.value==””)

{
alert(“Text box should not be empty”);
//reqtagelements.focus();
return false;
}
}

if(reqtagelements.type==”radio”)
{
if(reqtagelements.checked==””)
{
alert(“You should select one radiobutton”);
//reqtagelements.focus();
return false;
}

}

if(reqtagelements.type==”checkbox”)
{
if(reqtagelements.checked==false)
{
alert(“You should select atleast one checkbox”);
return false;

}

}

if(reqtagelements.type==”textarea”)
{

if(reqtagelements.value==””)
{
alert(“Textarea should not be empty”);

return false;

}
}

if(reqtagelements.selectedIndex==0)
{
alert(“Drop down should be selected”);
return false;
}

return true;

}

function concat_collection(objinput,objtextarea,objselect)
{

var mergearray = new Array;
var len1 = objinput.length;
var len2 = objtextarea.length;
var len3 = objselect.length;
for (i=0; i<len1; i++)
{
mergearray.push(objinput[i]);
}
for (i=0; i<len2; i++)
{
mergearray.push(objtextarea[i]);
}
for(i=0;i<len3;i++)
{
mergearray.push(objselect[i]);

}
return mergearray;

}

function validation(str, tagvalue)
{ var return_value;

switch (str)
{
case ’email’:
return_value= validate_email(tagvalue);
break;
case ‘numbers’:
return_value= validate_numbers(tagvalue);

break;

case ‘alphanumeric’:
return_value= validate_alphanumeric(tagvalue);

break;
case ‘html’:
return_value= validate_html(tagvalue);

break;
case ‘date’:
return_value= validate_date(tagvalue);
break;

}
return return_value;

}

function validate_email(tagvalue)
{ str=tagvalue.value

if(!str.match(/^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i))
{
alert(“Email Format is not valid”);

return false;
}

return true;
}

var dtCh= “/”;
var minYear=1900;
var maxYear=2100;

function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < “0”) || (c > “9”))) return false;
}
// All characters are numbers.
return true;
}

function stripCharsInBag(s, bag){
var i;
var returnString = “”;
// Search through string’s characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}

function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year &#37; 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}

function isDate(str){
var daysInMonth = DaysArray(12)
var pos1=str.indexOf(dtCh)
var pos2=str.indexOf(dtCh,pos1+1)
var strDay=str.substring(0,pos1)
var strMonth=str.substring(pos1+1,pos2)
var strYear=str.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)==”0″ && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)==”0″ && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)==”0″ && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert(“The date format should be : dd/mm/yyyy”)
return false
}
if (strMonth.length<1 || month<1 || month>12){
alert(“Please enter a valid month”)
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert(“Please enter a valid day”)
return false
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert(“Please enter a valid 4 digit year between “+minYear+” and “+maxYear)
return false
}
if (str.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(str, dtCh))==false){
alert(“Please enter a valid date”)
return false
}
return true
}

function validate_date(tagvalue){
var str=tagvalue.value;
if (isDate(str)==false){

return false
}
return true
}

function validate_numbers(tagvalue)
{
alert(tagvalue);
var str=tagvalue.value;
alert(str);
var ValidChars = “0123456789.”;
var IsNumber=true;
var Char;

for (i = 0; i < str.length && IsNumber == true; i++)
{
Char = str.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
alert(“Input should be Numeric”);

}

}
return IsNumber
}[/code]

I wud like to display an error message(“required fields cannot be left blank )on ssubmit of form

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@TcobbNov 30.2010 — The easiest way to accomplish this is to add a container element such as a DIV to your HTML, such as:
[CODE]<div id="error_Win" style = "display: none">
<span id = "errText">error message</span><br />
<input type = "button" value = "OKAY" onclick="hideBox()" />
</div>[/CODE]


Now for the javascript:

[CODE]function showError(message){
var x = document.getElementById("error_Win");
var y = document.getElementById("errText");
y.removeChild(y.firstChild);
var txt = document.createTextNode(message);
y.appendChild(txt);
x.style.display = "block";
}

function hideBox(){
var x = document.getElementById("error_Win");
x.style.display = "none";
}[/CODE]


Make sure that the span is originally seeded with some text, otherwise the code will break. Instead of using alert with the error message replace it with showError("the error message you want the user to see")
Copy linkTweet thisAlerts:
@ManasipradeepauthorDec 01.2010 — The problem with the above code here is that I am using the same div id for all the HTML elements.... so I guess when any of the fields fails validation,the error message will display in all the fields( since it is displaying using document.getElementById())..

Is there any way to alert the label names.... Like "Name should not be empty", "Email ID should not be empty"...?? But please keep it in mind that these fields are dynamically generated....
×

Success!

Help @Manasipradeep spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...