/    Sign up×
Community /Pin to ProfileBookmark

[NEWBIE] Syntax question regarding form validation script

Hiya!

I’m a newbie in the field of js, just finished my first website, still in volunteering.
OK, my problem is: I decided to apply some client side validation of the site’s forms. The following script will probably trigger some indignation amongst you, but this is my first script, practically copy-pasted from snippets I found on the web.
The first few lines of the script is the beginning of the validation function, interrupted by the definition of an alert customizing function. My first question is exactly about the place: did I well place this customizing thing, or could you suggest me a better way to place it?
After this definition within a definition, the validation script continues and calls/defines many times the removeCustomAlert function. That’s because of my second problem: originally, without the alert-customizing function, after the standard alert box had been closed, the related form field got focused. But the custom function stopped working after that the customized alert box had been applied, so finally I replaced the focus() function, right inside the removeCustomAlert function. That was the only way I could solve the issue, but gosh, it’s many many code. So my second question is: do you know an easier way to code this whole stuff?

Thanks in advance for all help and suggestions.

So, the code is:

[FONT=”Courier New”][SIZE=”2″][INDENT][INDENT]function checkForm() {
var cname, cemail, cfname, cfemail, cmessage;

with(window.document.frdForm)
{
cname = yourname;
cemail = yourmail;
cfname = friendsname;
cfemail = friendsmail;
cmessage = message; }

var ALERT_TITLE = “Oops!”;
var ALERT_BUTTON_TEXT = “Close”;

if(document.getElementById) {
window.alert = function(txt) {
createCustomAlert(txt);
}
}

function createCustomAlert(txt) {

d = document;

if(d.getElementById(“modalContainer”)) return;

mObj = d.getElementsByTagName(“body”)[0].appendChild(d.createElement(“div”));
mObj.id = “modalContainer”;

mObj.style.height = document.documentElement.scrollHeight + “px”;

alertObj = mObj.appendChild(d.createElement(“div”));
alertObj.id = “alertBox”;

if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + “px”;

alertObj.style.left = (d.documentElement.scrollWidth – alertObj.offsetWidth)/2 + “px”;

h1 = alertObj.appendChild(d.createElement(“h1”));
h1.appendChild(d.createTextNode(ALERT_TITLE));

msg = alertObj.appendChild(d.createElement(“p”));
msg.innerHTML = txt;

btn = alertObj.appendChild(d.createElement(“a”));
btn.id = “closeBtn”;
btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
btn.href = “#”;

btn.onclick = function() { removeCustomAlert();return false; }
}

if(trim(cname.value) == ”)
{
alert(‘Please enter your name’);
function removeCustomAlert() {document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”)); cname.focus();}
return false;
}
else if(trim(cemail.value) == ”)
{
alert(‘Please enter your email’);
function removeCustomAlert() {document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”)); cemail.focus();}
return false;
}
else if(!isEmail(trim(cemail.value)))
{
alert(‘Email address is not valid’);
function removeCustomAlert() {document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”)); cemail.focus();}
return false;
}

else if(trim(cfname.value) == ”)
{
alert(‘Please enter your friend’s name’);
function removeCustomAlert() {document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”)); cfname.focus();}
return false;
}
else if(trim(cfemail.value) == ”)
{
alert(‘Please enter your friend’s email’);
function removeCustomAlert() {document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”)); cfemail.focus();}
return false;
}
else if(!isEmail(trim(cfemail.value)))
{
alert(‘Email address is not valid’);
function removeCustomAlert() {document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”)); cfemail.focus();}
return false;
}
else if(trim(cmessage.value) == ”)
{
alert(‘Please enter your message’);
function removeCustomAlert() {document.getElementsByTagName(“body”)[0].removeChild(document.getElementById(“modalContainer”)); cmessage.focus();}cmessage.focus();
return false;
}

else
{
cname.value = trim(cname.value);
cemail.value = trim(cemail.value);
cfname.value = trim(cfname.value);
cfemail.value = trim(cfemail.value);
cmessage.value = trim(cmessage.value);

return true;
}
}

function trim(str)
{
return str.replace(/^s+|s+$/g,”);
}

function isEmail(str)
{
var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]).){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;

return regex.test(str);
} [/INDENT][/INDENT][/SIZE][/FONT]

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@tirnaMar 27.2010 — This is a 'skeleton' of the general form validation javascript I use.

Instead of 'alerting' at the end of it all the input fields that had errors you could change the colours of the error fields to red on the form in the function.

[CODE]
function validateForm() {
//get the form data
var name = Trim(document.getElementById("txtNewsletterName").value); //Trim() is a customised function
name = name.toLowerCase(); //assuming name must be lower case

var isDataValid = true; //flag showing whether any form data is valid or not

//initilaise an error message string
var errMsg = "** Error **nnThe following inputs are missing or invalid:nn";

//validate newsletter name
if(name == '' || name == null)
{
isDataValid = false;
errMsg = errMsg + "Newsletter name is invalid.nn";
}


//validate the rest of the form data


//after validating all the form data display any error messages
if(!isDataValid)
{
alert(errMsg);
return false;
}

//if form data is valid, write trimmed name back to where it came from for submission
document.getElementById("txtNewsletterName").value = name;

//at this point all form data is valid
return true;
}

[/CODE]
×

Success!

Help @lunule 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.24,
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,
)...