Writing Secure JavaScript


JavaScript to validate a form input securely


<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form Validation</title> <style> .error { color: red; } </style> </head> <body> <form id="myForm" onsubmit="return validateForm()"> <label for="username">Username:</label> <input type="text" id="username" name="username"><br> <span id="usernameError" class="error"></span><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br> <span id="passwordError" class="error"></span><br> <input type="submit" value="Submit"> </form> <script> function validateForm() { var username = document.getElementById("username").value; var password = document.getElementById("password").value; var usernameError = document.getElementById("usernameError"); var passwordError = document.getElementById("passwordError"); // Resetting error messages usernameError.innerHTML = ""; passwordError.innerHTML = ""; var isValid = true; // Validation rules if (username === "") { usernameError.innerHTML = "Username is required"; isValid = false; } if (password === "") { passwordError.innerHTML = "Password is required"; isValid = false; } // You can add more validation rules here return isValid; } </script> </body> 

</html> 

This example demonstrates basic form validation for a username and password field. The validateForm() function is called when the form is submitted. It checks if the username and password fields are empty. If any of them are empty, an error message will appear next to the respective field.

This is just a basic example to get you started. Depending on your requirements, you might want to add more validation rules and enhance security measures, such as preventing SQL injection or XSS attacks. Additionally, it's important to note that client-side validation like this should always be accompanied by server-side validation for enhanced security.


Comments

Popular posts from this blog

Google Hacking Guide

Sanitizing application text fields