[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:
function checkForm() {
var cname, cemail, cfname, cfemail, cmessage;
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 **\n\nThe following inputs are missing or invalid:\n\n";
//validate newsletter name
if(name == '' || name == null)
{
isDataValid = false;
errMsg = errMsg + "Newsletter name is invalid.\n\n";
}
//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;
}
Bookmarks