Skip to content
Snippets Groups Projects
Commit b7b17bd7 authored by Oshani Weerakoon's avatar Oshani Weerakoon
Browse files

Exercise 7 + Instructions

parent bb6bea3c
No related branches found
No related tags found
No related merge requests found
For this example, we'll use a simple HTML form with JavaScript for client-side validation. We won't need any additional libraries beyond what's provided by the browser's native JavaScript environment.
Here's how you can set it up:
1. **Install Node.js**: If you haven't already, install Node.js from [nodejs.org](https://nodejs.org/).
2. **Install `http-server`**: In your terminal or command prompt, install the `http-server` package globally using npm (Node.js package manager) so you can use it from any directory.
```bash
npm install -g http-server
```
3. **Create Files**: Create a directory for your project, and inside that directory, create two files: `index.html` and `validate.js`. Copy the HTML code into `index.html` and the JavaScript code into `validate.js`.
**HTML (index.html):**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
</head>
<body>
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" required>
<label for="age">Age:</label>
<input type="number" id="age" min="18" max="99" required>
<button type="submit">Submit</button>
</form>
<script src="validate.js"></script>
</body>
</html>
```
In the HTML above, we have a form with two inputs: one for email and one for age. The `type`, `min`, `max`, and `required` attributes provide built-in HTML5 validation.
**JavaScript (validate.js):**
```javascript
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('myForm');
form.addEventListener('submit', (event) => {
// Prevent the default form submission
event.preventDefault();
// Perform validation
const email = form.elements['email'].value;
const age = form.elements['age'].value;
if (!validateEmail(email) || !validateAge(age)) {
alert('Please provide a valid email and age.');
return;
}
// If validation passes, proceed with form submission
// Here you would typically use fetch or XMLHttpRequest to send the data
console.log('Form submitted', { email, age });
// fetch('/submit-form', { method: 'POST', body: JSON.stringify({ email, age }) })
// .then(/* ... */)
// .catch(/* ... */);
});
});
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
function validateAge(age) {
return age >= 18 && age <= 99;
}
```
4. **Start the Server**: Navigate to your project directory in the terminal and run the `http-server` command.
```bash
cd path/to/your/project-directory
http-server
```
After running the command, `http-server` will start serving your files on a local server, typically on port 8080. You'll see output similar to this:
```plaintext
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.1.2:8080
Hit CTRL-C to stop the server
```
5. **Access the Form**: Open your web browser and go to `http://localhost:8080`. You should see your form displayed. Try submitting the form with invalid data, and you'll see the JavaScript validation in action, preventing the form from being submitted.
6. **Form Submission**: To actually submit the form to a server, you would need a server-side script to handle the POST request. Since this example is for client-side validation only, the form submission is simulated with a `console.log` statement. In a real-world scenario, you would replace this with an AJAX request (using `fetch` or `XMLHttpRequest`) to a server-side endpoint that accepts and processes the form data.
Note: `http-server` serves files only and does not process server-side scripts. If you want to handle form submissions, you would need a more complex server setup, such as an Express.js application in Node.js, which can handle POST requests and interact with a database or other services.
7. **Conclusion**:
This example demonstrates how you can use native HTML5 form validation features along with custom JavaScript validation to ensure data integrity before it's sent across the network, thus adhering to green programming practices by reducing unnecessary data transmission and server load.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
</head>
<body>
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" required>
<label for="age">Age:</label>
<input type="number" id="age" min="18" max="99" required>
<button type="submit">Submit</button>
</form>
<script src="validate.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('myForm');
form.addEventListener('submit', (event) => {
// Prevent the default form submission
event.preventDefault();
// Perform validation
const email = form.elements['email'].value;
const age = form.elements['age'].value;
if (!validateEmail(email) || !validateAge(age)) {
alert('Please provide a valid email and age.');
return;
}
// If validation passes, proceed with form submission
// Here you would typically use fetch or XMLHttpRequest to send the data
console.log('Form submitted', { email, age });
// fetch('/submit-form', { method: 'POST', body: JSON.stringify({ email, age }) })
// .then(/* ... */)
// .catch(/* ... */);
});
});
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
function validateAge(age) {
return age >= 18 && age <= 99;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment