How can I effectively reduce the number of rows in my code?

javascript

#1

So I can see repetitive patterns in my code which I would like to compress and reduce some rows in my code. Username, Firstname and Lastname have the same validations. But I'm not sure how I could compress them into one function.

Here is my .html file:

Here is my .js file:

function validateName()
{

var name = document.getElementById("commentName").value;  

if(name.length == 0)
{

	producePrompt("Name is required", "commentNamePrompt", "red");
	return false;
}

if(!name.match(/^[a-zA-Z]+$/))
{

	producePrompt("First Name Please", "commentNamePrompt", "red");
	return false;

}

producePrompt("Name is Valid", "commentNamePrompt", "green");
return true;

}

function validateLastName()
{

var lastName = document.getElementById("commentLastName").value;

if(lastName.length == 0)
{

	producePrompt("Lastname is required", "commentLastNamePrompt", "red");
	return false;
}

if(!lastName.match(/^[a-zA-Z]+$/))
{

	producePrompt("Lastname Please", "commentLastNamePrompt", "red");
	return false;

}

producePrompt("Lastname is Valid", "commentLastNamePrompt", "green");
return true;

}

function validateEmail()
{

var email = document.getElementById("commentEmail").value;

if(email.length == 0)
{

	producePrompt("Email is required", "commentEmailPrompt", "red");
	return false;
}

if(!email.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/))
{

	producePrompt("Email Please", "commentEmailPrompt", "red");
	return false;

}

producePrompt("Email is Valid", "commentEmailPrompt", "green");
return true;

}

function validateUsername()
{

var username = document.getElementById("commentUsername").value;

if(username.length == 0)
{

	producePrompt("Username is required", "commentUsernamePrompt", "red");
	return false;
}

if(!username.match(/^[a-zA-Z]+$/))
{

	producePrompt("Username Please", "commentUsernamePrompt", "red");
	return false;

}

producePrompt("Username is Valid", "commentUsernamePrompt", "green");
return true;

}

function validateUsername()
{

var username = document.getElementById("commentUsername").value;

if(username.length == 0)
{

	producePrompt("Username is required", "commentUsernamePrompt", "red");
	return false;
}

if(!username.match(/^[a-zA-Z]+$/))
{

	producePrompt("Username Please", "commentUsernamePrompt", "red");
	return false;

}

producePrompt("Username is Valid", "commentUsernamePrompt", "green");
return true;

}

function producePrompt(message, promptLocation, color )
{

document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;

}


#2

This post was flagged by the community and is temporarily hidden.