javascript form validation for empty field and wrong input - javascript

this program runs correctly.. my task is, when name field left empty then (please enter your name )this error will be generated and when i type wrong input(like numbers)then (only alphabets and white space are allowed)this error message has to be generate. how can i do this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validation tutorial</title>
<script>
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.borderColor ='#3BFF3B';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else if(document.getElementById(x).value === ''){
//This is for an empty string or if name was not entered.
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error2').style.display = "block";
return false;
}else{
// Style red
document.getElementById(x).style.borderColor ='#FF0000';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(email)){
document.getElementById('email').style.borderColor ='#3BFF3B';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.borderColor ='#FF0000';
return false;
}
}
// Validate Select boxes
function validateSelect(x){
if(document.getElementById(x).selectedIndex !== 0){
document.getElementById(x).style.borderColor ='#3BFF3B';
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
document.getElementById(x).style.borderColor ='#FF0000';
return false;
}
}
function validateRadio(x){
if(document.getElementById(x).checked){
return true;
}else{
return false;
}
}
function validateCheckbox(x){
if(document.getElementById(x).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate animal dropdown box
if(!validateSelect('subject')){
document.getElementById('subjectError').style.display = "block";
error++;
}
// Validate Radio
if(validateRadio('male')){
}else if(validateRadio('female')){
}else{
document.getElementById('genderError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validateForm()">
<label for="name">Name</label>
<input type="text" name="name" id="name" onblur="validateName(name)" />
<span id="nameError" style="display: none;">only alphabates and white space are allowed</span>
<span id="nameError2" style="display: none;">please enter a name</span>
<br><br>
<label for="email">Email</label>
<input type="text" name="email" id="email" onblur="validateEmail(value)" />
<span id="emailError" style="display: none;">You must enter a valid email address</span>
<br><br>
<label for="hand">Gender</label>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" onblur="validateRadio(id)" />
<label for="left">male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" onblur="validateRadio(id)" />
<label for="right">female</label>
</li>
</ul>
<span class="validateError" id="genderError" style="display: none;">Please select gender</span>
<br><br>
<label for="subject">Favourite Subject</label>
<select name="subject" id="subject" onblur="validateSelect(name)">
<option value="">SUBJECTS</option>
<option value="php">PHP</option>
<option value="java">JAVA</option>
<option value="sql">SQL</option>
</select>
<span class="validateError" id="subjectError" style="display: none;">You must select your favourite subject</span>
<br><br>
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
</body>
</html>
There are much better ways to do this. This is not an elegant way. I see this code is from an example or tutorial. Please check other tutorials on this subject, as this is just a quick way of implementing what you want.

Related

Disabling a button on empty <select> list?

`I've created a form that allows a user to enter their details and have their first and last names displayed along with a numerical ID. There is a 'Delete' button allowing the user to remove whatever name they select.
by default, the 'Delete' button should be disabled until the <select> list is populated. If all names are deleted from the list - the 'Delete' button should disable again.
That's where im struggling. I cant get the 'Delete' button to enable when a name is added to the list.
Below is my HTML and JavaScript:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.value === 1;
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
console.log("is remove being triggered??")
}
if (Member.options.length == ""){
Delete.disabled = true
}
else {
Delete.disabled = false
}
</script>
</body>
`
The reason why the Delete button is not enabling is because the code that is supposed to enable the Delete button is only run once, when the page loads.
Assuming that this is the code that is supposed to enable the button:
if (Member.options.length == 0){ // changed from Member.options.length == ""
Delete.disabled = true
} else {
Delete.disabled = false
}
This code is only run once, when the page loads and the JavaScript code is run. In order to enable the button properly, we need to run this code every time that Member.options.length changes. One way you can do this is place the code snippet above for disabling/enabling the Delete button inside the onclick listener for the save button and to re-check every time a new user is saved. You would have to add this snippet into every place in your code where Member.options.length could change (inside the listener for the delete button as well).
Full updated code:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.options.length == 0
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
if (Member.options.length == 0){
Delete.disabled = true
}
else {
Delete.disabled = false
}
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
if (Member.options.length == 0) {
Delete.disabled = true
}
else {
Delete.disabled = false
}
console.log("is remove being triggered??")
}
</script>
</body>
so if i understood correctly you want to toggle a button if a is populated
In that case you want to keep track of the options
You can use
document.querySelectoAll('options')
and store it in a variable
then write a function that check if there's a value in that variable and disable or enable the button based on that.
Here's a fiddle:
https://jsfiddle.net/skm7bcr6/15/

Inserting regular expression for verifying URL address and email address

I need to insert a regular expression to verify the input for URL and email is valid, so where would this go in the code to make it work without messing with anything else? I need to know exactly where it would go and how it would look.
window.onload = function() {
document.getElementById('ifBusiness').style.display = 'none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if (is_business) {
document.getElementById('ifBusiness').style.display = 'block';
document.getElementById('ifResidence').style.display = 'none';
} else {
document.getElementById('ifBusiness').style.display = 'none';
document.getElementById('ifResidence').style.display = 'block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if (address.value == "") {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the bname, tax and url if a business is selected
if (is_business) {
if (bname.value == "") {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
if (tax.value == "") {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if (url.value == "") {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if (rname.value == "") {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if (email.value == "") {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open('', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusb ar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234');
// Set the form target to the name of the newly created popup.
var form = document.querySelector('form[name="myForm"]');
form.setAttribute('target', 'SELU');
return true;
}
head {
text-align: center;
}
body {
text-align: center;
}
.bold {
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h1>Fill the form below</h1>
<!-- center tag is deprecated and should be replaced by CSS -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="text" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
<hr>
<hr>
</body>
</html>
To validate whether or not a user is inputting an url/email, simply change your input type to "url" or "email" and it will be validated for you.
Like so:
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="url" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="email" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>

Javascript Error message flashes for only a second [duplicate]

This question already has answers here:
What is the meaning of onsubmit="return false"? (JavaScript, jQuery)
(4 answers)
Closed 5 years ago.
I have this HTML project that validates an empty form. The error is being displayed on the side of the inputs but only flashes for a second. I just want the error of the messages to be displayed once
This is my HTML code with the necessary links:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - JQuery </title>
<link rel="stylesheet" type="text/css" href="contactform.css">
</head>
<body>
<h1 id="pageheading">Zedland Health Authority</h1>
<h2 class="sectionheading">Contact Form</h2>
<form id="register">
<fieldset id="controls">
<div>
<label class="formlabel" for="fname">First Name: </label>
<input id="fname" type="text" size="30" placeholder="First name"
autofocus>
<p id="fname-error" class="error" style="display:none; color:red;">*
You must enter a first name.</p>
</div>
<div>
<label class="formlabel"for="lname">Last Name: </label>
<input id="lname" type="text" size="30">
<p id="lname-error" class="error" style="display:none; color:red;">*
You must enter a Last name.</p>
</div>
<div>
<label class="formlabel" for="title">Title: </label>
<select id="title">
<option value="Mr">Mr.</option>
<option value="Ms">Ms.</option>
<option value="Mrs">Mrs.</option>
<option value="Miss">Miss.</option>
<option value="Master">Master.</option>
</select>
</div>
<div>
<label class="formlabel" for="heathauthoritynumber"><span>
<img src="tooltip.png" id="qmark" alt="Hint"></span>
Health Authority Number:
</label>
<input id="healthauthoritynumber" type="text" size="10">
<p id="hn-error" class="error" style="display:none; color:red;">*You
must enter a Health Authority Number eg('ZHA345742)</p>
<div class="tooltip" id="ttip">If you do not know your ZHA number
,please contact your GP</div>
</div>
<div>
<label class="formlabel" for="email">Email: </label>
<input id="email" type="text" size="40">
<p id="email-error" class="error" style="display:none; color:red;">You
must enter email</p>
</div>
<div>
<label class="formlabel" for="telephone">Telephone Number: </label>
<input id="telephone" type="text" size="40">
<p id="tele-error" class="error" style="display:none; color:red;">You
must enter a telephone</p>
</div>
<div class="formlabel">
<input id="submit-button" type="submit" value="Submit" >
</div>
</fieldset>
</form>
<script src="contactform.js"></script>
</body>
</html>
This is my Javascript
function onSubmit(){
console.log("ive been submitted");
checkEmpty(document.getElementById('fname'),document.getElementById("fname-error"));
checkEmpty(document.getElementById('lname'),document.getElementById("lname-error"));
checkEmpty(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
checkEmpty(document.getElementById('email'),document.getElementById("email-error"));
checkEmpty(document.getElementById('telephone'),document.getElementById("tele-error"));
//checkValidHealthID(document.getElementById('healthauthoritynumber'),document.getElementById("hn-error"));
}
// Read about regular expressions using: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
// and http://stackoverflow.com/questions/25155970/validating-uk-phone-number-regex-c
function checkValidHealthID(inputID, errorID){
var re = new RegExp('/ZHA\d{6}$/');
if((inputID.value)!== re){
errorID.style.display = "inline";
}else
{
errorID.style.display = "none";
}
}
function checkEmpty(inputID, errorID){
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
console.log("checking empty");
if((inputID.value === "") || (inputID.value.length === 0)){
console.log("empty!!");
errorID.style.display = "inline";
}
else
{
errorID.style.display = "none";
}
}
function textHint(txtElem, defaultText) {
txtElem.value = defaultText;
txtElem.style.color = "#A8A8A8";
txtElem.style.fontStyle = "italic";
txtElem.onfocus = function() {
if (this.value === defaultText) {
this.value = "";
this.style.color = "#000";
this.style.fontStyle = "normal";
}
}
txtElem.onblur = function() {
if (this.value === "") {
this.value = defaultText;
this.style.color = "#A8A8A8";
this.style.fontStyle = "italic";
}
}
}
function textHints() {
//textHint(document.getElementById("firstName"), "Enter your first name");
textHint(document.getElementById('lname'), "Enter your last name");
textHint(document.getElementById('healthauthoritynumber'), "for eg
,ZHA346783");
textHint(document.getElementById('email'), "Enter your email");
textHint(document.getElementById('telephone'), "Enter your telephone
number");
}
function switchToolTip() {
document.getElementById('qmark').onmouseover = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='block';
}
document.getElementById('qmark').onmouseout = function() {
var toolTip = document.getElementById('ttip');
toolTip.style.display='none';
}
}
//windows.onload=textHints();
//windows.onload=switchToolTip();
//window.onload=init;
document.getElementById("submit-button").onclick = onSubmit;
Your form is getting submitted which results in page reload. That's why you see the message flashing for a while. I saw the commented line in your JavaScript
//Default behaviour at for FORM is to reload the HTML page
//e.preventDefault();
You should get uncomment e.preventDefault().
Grab the click event as function onSubmit(event) and pass the event to checkEmpty.

JavaScript Inline Validation not Working

I'm trying Javascript inline form validation for the first time. I borrowed the code from another website and have done everything suggested to get it correct but it's still not working. It's supposed to turn the form box red if info is wrong and print a message underneath the incorrect box and turn it green if the info entered is correct. Please help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Request Info</title>
<link href="bnb stylesheet.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:400,700,800' rel='stylesheet' type='text/css'>
<style type="text/css">
.sidebar1 {
float: right;
width: 180px;
background-color: #9CBEEF;
padding-bottom: 10px;
}
</style>
<script>
//Script validation coding borrowed from Philip Brown on Culttt.com
//culttt.com/2012/08/08/really-simple-inline-javascript-validation/
//Validation
function validateName(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(x).value)){
// Style green
document.getElementById(x).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.background ='#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
function validateName(lname){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(lname).value)){
// Style green
document.getElementById(lname).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(lname + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(lname).style.background ='#e35152';
// Show error prompt
document.getElementById(lname + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(re.test(document.getElementById(email).value)){
document.getElementById('email').style.background ='#ccffcc';
document.getElementById('emailError').style.display = "none";
return true;
}else{
document.getElementById('email').style.background ='#e35152';
return false;
}
}
//Validate phone
function validatePhone(phone){
// Validation rule
var re = /[0-9-']$/;
// Check input
if(re.test(document.getElementById(phone).value)){
// Style green
document.getElementById(phone).style.background ='#ccffcc';
//Validate Comments
function validateComment(x){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if(re.test(document.getElementById(comment).value)){
// Style green
document.getElementById(comment).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.background ='#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Hide error prompt
document.getElementById(x + 'Error').style.display = "none";
return true;
}else{
// Style red
document.getElementById(x).style.background ='#e35152';
// Show error prompt
document.getElementById(x + 'Error').style.display = "block";
return false;
}
}
// Validate Select boxes
function validateCheckbox(terms){
if(document.getElementById(terms).checked){
return true;
}
return false;
}
function validateForm(){
// Set error catcher
var error = 0;
// Check name
if(!validateName('name')){
document.getElementById('nameError').style.display = "block";
error++;
}
//Validate last name
if(!validateName('lname')){
document.getElementById('nameError').style.display = "block";
error++;
}
//Validate phone
if(!validatePhone('phone')){
document.getElementById('phoneError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
//Validate message
if(!validateComment('comment')){
document.getElementById('commentError').style.display = "block";
error++;
}
//Validate Checkbox
if(!validateCheckbox('terms')){
document.getElementById('termsError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if(error > 0){
return false;
}
}
</script>
</head>
<body>
<div class="container">
<div class="header"><img src="images/logo 3.png" alt="Insert Logo Here" name="Insert_logo" width="980" height="200" id="Insert_logo" style="background-color: #9cbeef; display:block;" />
</div>
<div id="navcontainer">
<ul id="navlist1">
<li id="active1">Home</li>
<li>Host</li>
<li>Guest</li>
<li>About Us</li>
<li>Request Info</li>
</ul>
</div> </div>
<div class="content">
<div class="content">
<h1>Contact</h1>
<form action="Request Info2.html" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Required Information</legend>
<table cellpadding="3">
<tr><td><label for="name"><strong>First Name:</strong></label></td><td>
<input type="text" name="name" id="name" maxlength="30" onblur="validateName(name)" placeholder="Johnny"/>
<span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="lname"><strong>Last Name:</strong></label></td><td>
<input type="text" name="lname" id="lname" maxlength="30" onblur="validateName(lname)" placeholder="Smith"/>
<span id="lnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="email"><strong>Email:</strong></label></td><td>
<input type="text" name="email" id="email" maxlength="75" onblur="validateEmail(email)" placeholder="johndoe#email.com"/>
<span id="emailError" style="display: none;">You can must enter a valid email address</span></td></tr>
<tr><td><label for="phone"><strong>Phone:</strong></label></td><td>
<input type="text" name="phone" id="phone" maxlength="11" onblur="validatePhone(phone)" placeholder="303-777-7777"/>
<span id="phoneError" style="display: none;">You can only use numbers</span></td></tr>
<tr><td><strong><label for="comment">Comments:</strong></label>
</td><td>
<textarea input type="text" name="comment" id="comment" textarea rows="10" cols="30"maxlength="500" >
</textarea>
<span class="validateComment" id="commentError" style="display: none;">Please leave us your comments</span></td></tr>
</table>
</fieldset>
<fieldset style="text-align: center" >
<label ="terms"><strong>Terms and Conditions</strong></label><br>
<p>Please read our Privacy Policy before submitting. We will always protect your privacy. You have the ability to change, update or terminate your information on the site at anytime you choose. B-n-B Concierges also reserves the right to remove any person from the site at their discretion. </p>
<br/>
I confirm that I agree with terms & conditions
<input type="checkbox" name="terms" id="accept" value="accept" maxlength="10" onblur="validateCheckbox(terms)" />
<span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span>
</fieldset>
<fieldset>
<input type="submit" id="submit" name="submit" value="Submit" />
</fieldset>
</form>
</div>
</div>
<div class="footer">
<p><div id="navcontainer">
<ul id="navlist2">
<li id="active2"><a href="Policies.html" >Conditions</a></li>
<li>Privacy</li>
<li>Sign Up</li>
<li>© 2014 Heidi Medina</li>
</ul>
</div>
</div>
</body>
</html>
#user3446663:
The following code works. Note that I have left the form action property empty because you had a space in the name of the form you were referring to (Request Info2.html). You'll want to either put an underscore in that file name so it reads 'Request_Info2.html' or remove the space so it reads 'RequestInfo2.html' in order to have the file name be recognized properly. Here's the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Request Info</title>
<link href="bnb stylesheet.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:400,700,800' rel='stylesheet' type='text/css'>
<style type="text/css">
.sidebar1 {
float: right;
width: 180px;
background-color: #9CBEEF;
padding-bottom: 10px;
}
</style>
<script>
//Script validation coding borrowed from Philip Brown on Culttt.com
//culttt.com/2012/08/08/really-simple-inline-javascript-validation/
// Validate first/last name
function validateName(name){
// Validation rule
var re = /[A-Za-z -']$/;
// Check input
if (re.test(document.getElementById(name).value)){
// Style green
document.getElementById(name).style.background ='#ccffcc';
// Hide error prompt
document.getElementById(name + 'Error').style.display = "none";
return true;
} else {
// Style red
document.getElementById(name).style.background ='#e35152';
// Show error prompt
document.getElementById(name + 'Error').style.display = "block";
return false;
}
}
// Validate email
function validateEmail(email){
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (re.test(document.getElementById(email).value)){
document.getElementById(email).style.background ='#ccffcc';
document.getElementById(email + 'Error').style.display = "none";
return true;
} else {
document.getElementById(email).style.background ='#e35152';
document.getElementById(email + 'Error').style.display = "block";
return false;
}
}
//Validate Comments
function validateComment(comment){
var re = /[A-Za-z -']$/;
if (re.test(document.getElementById(comment).value)){
document.getElementById(comment).style.background ='#ccffcc';
document.getElementById(comment + 'Error').style.display = "none";
return true;
} else {
document.getElementById(comment).style.background ='#e35152';
document.getElementById(comment + 'Error').style.display = "block";
return false;
}
}
//Validate phone
function validatePhone(phone){
var re = /[0-9-']$/;
if(re.test(document.getElementById(phone).value)){
document.getElementById(phone).style.background ='#ccffcc';
document.getElementById(phone + 'Error').style.display = "none";
return true;
} else {
document.getElementById(phone).style.background ='#e35152';
document.getElementById(phone + 'Error').style.display = "block";
return false;
}
}
// Validate checkbox
function validateCheckbox(terms){
if(document.getElementById(terms).checked){
document.getElementById(terms + 'Error').style.display = "none";
return true;
} else {
document.getElementById(terms + 'Error').style.display = "block";
return false;
}
}
// Validate Form
function validateForm(){
// Set error catcher
var error = 0;
// Validate first name
if (!validateName('fname')){
document.getElementById('fnameError').style.display = "block";
error++;
}
//Validate last name
if (!validateName('lname')){
document.getElementById('lnameError').style.display = "block";
error++;
}
//Validate phone
if (!validatePhone('phone')){
document.getElementById('phoneError').style.display = "block";
error++;
}
// Validate email
if (!validateEmail('email')){
document.getElementById('emailError').style.display = "block";
error++;
}
//Validate message
if (!validateComment('comment')){
document.getElementById('commentError').style.display = "block";
error++;
}
//Validate checkbox
if (!validateCheckbox('terms')){
document.getElementById('termsError').style.display = "block";
error++;
}
// Don't submit form if there are errors
if (error > 0){
return false;
}
}
</script>
</head>
<body>
<div class="container">
<div class="header">
<a href="Request Info.html">
<img src="images/logo 3.png" alt="Insert Logo Here" name="Insert_logo" width="980" height="200" id="Insert_logo" style="background-color: #9cbeef; display:block;" />
</a>
</div>
<div id="navcontainer">
<ul id="navlist1">
<li id="active1">Home</li>
<li>Host</li>
<li>Guest</li>
<li>About Us</li>
<li>Request Info</li>
</ul>
</div>
</div>
<div class="content">
<h1>Contact</h1>
<form action="" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Required Information</legend>
<table cellpadding="3">
<tr><td><label for="name"><strong>First Name:</strong></label></td><td>
<input type="text" name="fname" id="fname" maxlength="30" onblur="validateName(name)" placeholder="Johnny"/>
<span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="lname"><strong>Last Name:</strong></label></td><td>
<input type="text" name="lname" id="lname" maxlength="30" onblur="validateName(name)" placeholder="Smith"/>
<span id="lnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span></td></tr>
<tr><td><label for="email"><strong>Email:</strong></label></td><td>
<input type="text" name="email" id="email" maxlength="75" onblur="validateEmail(name)" placeholder="johndoe#email.com"/>
<span id="emailError" style="display: none;">You can must enter a valid email address</span></td></tr>
<tr><td><label for="phone"><strong>Phone:</strong></label></td><td>
<input type="text" name="phone" id="phone" maxlength="11" onblur="validatePhone(name)" placeholder="303-777-7777"/>
<span id="phoneError" style="display: none;">You can only use numbers</span></td></tr>
<tr><td><strong><label for="comment">Comments:</strong></label></td><td>
<textarea input type="text" name="comment" id="comment" textarea rows="10" cols="30"maxlength="500" onblur="validateComment(name)" ></textarea>
<span class="validateComment" id="commentError" style="display: none;">Please leave us your comments</span></td></tr>
</table>
</fieldset>
<fieldset style="text-align: center" >
<label ="terms"><strong>Terms and Conditions</strong></label><br>
<p>Please read our Privacy Policy before submitting. We will always protect your privacy.
You have the ability to change, update or terminate your information on the site at anytime you choose. B-n-B
Concierges also reserves the right to remove any person from the site at their discretion.</p><br/>
I confirm that I agree with terms & conditions
<input type="checkbox" name="terms" id="terms" value="accept" maxlength="10" onblur="validateCheckbox(name)" />
<span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span>
</fieldset>
<fieldset>
<input type="submit" id="submit" name="submit" value="Submit" />
</fieldset>
</form>
</div>
<div class="footer">
<div id="navcontainer">
<ul id="navlist2">
<li id="active2"><a href="Policies.html" >Conditions</a></li>
<li>Privacy</li>
<li>Sign Up</li>
<li>© 2014 Heidi Medina</li>
</ul>
</div>
</div>
</body>
</html>
I do not believe this warrants an answer, but I do not have enough reputation to comment as of yet.
Consider using HTML5 patterns if possible.
Examples:
http://html5pattern.com/Names
Polyfill:
https://github.com/ryanseddon/H5F
Most of the time simply specifying the input type is enough (phone, email)
<input type="email" name="" value="" required />
You can fine-tune the validation with the pattern attribute
<input type="text" pattern="[a-zA-Z0-9]+">
There are few minor issues in the code.
ID values are wrongly provided in your JS code
Eg: you have fnameError as ID to display error in firstname.
<span id="fnameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
Whereas in the Javascript, you have used just nameError
document.getElementById('nameError').style.display = "block";
Similar kind of spelling issue is there in lastname also.. fix if there is anymore reference issues because of spelling differences, then you are good to go.

Javascript form validation - can't validate multiple fields

I am trying to get a form with multiple fields validate when the submit button is pressed.
If a field is invalid then a message appears next to the field. I can get one of the invalid messages to appear but not all of them. The function I am using is below.
function checkForm() {
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("errEmail").style.display="inline";
return false;
}
if(document.getElementById("fname").value==""){
document.getElementById("errfName").style.display="inline";
return false;
}
else {
return true;
}
if(document.getElementById("lname").value==""){
document.getElementById("errlName").style.display="inline";
return false;
}
else {
return true;
}
}
}
html below
<form name ="reg" id="test">
<fieldset id="controls">
<div>
<label for="title">Title: </label>
<select id="titles">
<option value="mr" selected="selected">Title</option>
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
<option value="ms">Ms.</option>
<option value="miss">Miss</option>
</select>
</div>
<div>
<label for="fname">First Name: </label>
<input id="fname" type="text"><span id="errfName" class="error">* Please Enter a First Name</span>
</div>
<div>
<label for="lname">Last Name: </label>
<input id="lname" type="text"><span id="errlName" class="error">* Please Enter a Last Name</span>
</div>
<div>
<label for="email">Email: </label>
<input id="email" type="text" size="40"><span id="errEmail" class="error">* Please enter a valid email</span>
</div>
<div>
<input type="submit" value="submit">
</div>
</fieldset>
</form>
</body>
</html>
try this:
function checkForm() {
var errors = [];
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
errors.push("errEmail");
}
if(document.getElementById("fname").value==""){
errors.push("errfName");
}
if(document.getElementById("lname").value==""){
errors.push("errlName");
}
if(errors.length > 0 ){
for(var i=0;i<errors.length;i++){
document.getElementById(errors[i]).style.display="inline";
}
return false;
}else{
return true
}
}
}

Categories

Resources