Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to avoid inserting NULL values to a table with JavaScript?
When building dynamic tables with JavaScript, it's important to validate user input and prevent NULL values from being inserted. This ensures data integrity and provides a better user experience.
Understanding NULL Validation
In JavaScript, we need to check for null, undefined, and empty strings before inserting values into a table. The basic condition structure is:
while (!(variable1 == null || variable2 == null || variable3 == null)) {
// Insert values only when none are null
}
Complete Example with Validation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Avoid NULL Values in Table</title>
<style>
table { border-collapse: collapse; margin: 20px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
caption { font-weight: bold; margin-bottom: 10px; }
</style>
</head>
<body>
<h2>Dynamic Table with NULL Validation</h2>
<p>This example demonstrates how to prevent NULL values in a JavaScript table.</p>
<script>
var firstNameArray = [];
var lastNameArray = [];
var index = 0;
var firstName = "";
var lastName = "";
// Collect user input while avoiding NULL values
while (!(firstName === null || lastName === null)) {
firstName = prompt("Enter your First Name (Cancel to finish):");
if (firstName === null) break;
lastName = prompt("Enter your Last Name (Cancel to finish):");
if (lastName === null) break;
// Validate that inputs are not empty or just whitespace
if (firstName.trim() !== "" && lastName.trim() !== "") {
firstNameArray[index] = firstName.trim();
lastNameArray[index] = lastName.trim();
index++;
} else {
alert("Please enter valid names (not empty).");
}
}
// Create and display the table
function createTable() {
let tableHTML = "";
tableHTML += "<table>";
tableHTML += "<caption>User Information Table</caption>";
tableHTML += "<tr><th>First Name</th><th>Last Name</th></tr>";
for (let i = 0; i < firstNameArray.length; i++) {
if (firstNameArray[i] !== null && lastNameArray[i] !== null) {
tableHTML += "<tr>";
tableHTML += "<td>" + firstNameArray[i] + "</td>";
tableHTML += "<td>" + lastNameArray[i] + "</td>";
tableHTML += "</tr>";
}
}
tableHTML += "</table>";
document.getElementById("tableContainer").innerHTML = tableHTML;
}
// Display the table if we have data
if (firstNameArray.length > 0) {
createTable();
} else {
document.getElementById("tableContainer").innerHTML = "<p>No data entered.</p>";
}
</script>
</body>
</html>
Key Validation Techniques
Here are the essential validation methods to prevent NULL values:
<!DOCTYPE html>
<html>
<body>
<script>
// Method 1: Check for null and undefined
function isValid(value) {
return value !== null && value !== undefined && value !== "";
}
// Method 2: Check for empty or whitespace strings
function isNotEmpty(value) {
return value != null && value.trim() !== "";
}
// Method 3: Comprehensive validation
function validateInput(value) {
if (value === null || value === undefined) {
console.log("Value is null or undefined");
return false;
}
if (typeof value === "string" && value.trim() === "") {
console.log("Value is empty string");
return false;
}
return true;
}
// Test the validation functions
console.log("Testing validation:");
console.log("isValid('John'):", isValid('John'));
console.log("isValid(null):", isValid(null));
console.log("isValid(''):", isValid(''));
console.log("isNotEmpty(' '):", isNotEmpty(' '));
console.log("validateInput('Valid'):", validateInput('Valid'));
</script>
</body>
</html>
Testing validation:
isValid('John'): true
isValid(null): false
isValid(''): false
isNotEmpty(' '): false
validateInput('Valid'): true
Best Practices
-
Always validate input: Check for
null,undefined, and empty strings - Use trim(): Remove leading/trailing whitespace before validation
- Provide user feedback: Alert users when invalid data is entered
-
Use strict comparison: Use
===instead of==for precise NULL checks
Alternative Approach with Form Validation
<!DOCTYPE html>
<html>
<body>
<form id="userForm">
<input type="text" id="firstName" placeholder="First Name" required>
<input type="text" id="lastName" placeholder="Last Name" required>
<button type="submit">Add to Table</button>
</form>
<table id="userTable" style="border-collapse: collapse; margin-top: 20px;">
<tr><th style="border: 1px solid #ddd; padding: 8px;">First Name</th>
<th style="border: 1px solid #ddd; padding: 8px;">Last Name</th></tr>
</table>
<script>
document.getElementById('userForm').addEventListener('submit', function(e) {
e.preventDefault();
const firstName = document.getElementById('firstName').value.trim();
const lastName = document.getElementById('lastName').value.trim();
// Validate inputs are not empty
if (firstName && lastName) {
addRowToTable(firstName, lastName);
// Clear form
document.getElementById('firstName').value = '';
document.getElementById('lastName').value = '';
} else {
alert('Please fill in both fields.');
}
});
function addRowToTable(firstName, lastName) {
const table = document.getElementById('userTable');
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
cell1.textContent = firstName;
cell2.textContent = lastName;
cell1.style.border = "1px solid #ddd";
cell1.style.padding = "8px";
cell2.style.border = "1px solid #ddd";
cell2.style.padding = "8px";
}
</script>
</body>
</html>
Conclusion
Preventing NULL values in JavaScript tables requires proper input validation using checks for null, undefined, and empty strings. Always validate user input before adding data to ensure table integrity and provide a better user experience.
Advertisements
