Reputation: 81
so i got a contacts.json file in which i'll store what i will submit from my form in the contact page. The 'storing' works well, just i want to add a validation to it, and only after that validation to be able to send and store those so called contacts. here's what i have:
app.js:
app.post('/contact', function(req, res) {
console.log(req.body);
const contacts_path = __dirname + '/privat/contacts.json';
const contactDataJson = fs.readFileSync(contacts_path);
const json_data = JSON.parse(contactDataJson);
const contact = {
email: req.body.email,
content: req.body.content
}
json_data["contacts"].push(contact);
fs.writeFileSync(contacts_path, JSON.stringify(json_data));
res.sendFile(__dirname + '/static/contact.html');
});
html:
<div id="container">
<div class="form-wrap">
<form method="POST" action="/contact">
<h1>Share your thoughts!</h1>
<p>Email</p>
<input id="email" name="email" placeholder="Type here your email" type="text"><br><br>
<p>Tell us what you think about us!</p>
<textarea id="content" name="content" class="contactarea" rows="10" placeholder="What would you like to talk about?"></textarea><br><br>
<button type="submit" class="btn">
<i class="fas fa-sign-in-alt"></i>submit
</button>
</form>
</div>
</div>
Upvotes: 1
Views: 253
Reputation: 473
The validation you want to do is on the client side, so you need to perform it before the form is posted to your backend service (app.js
). In order to do so, you can add a handler to the submit action, which would invoke the validation method and then submit the form. Something like:
<div id="container">
<div class="form-wrap">
<form id="myForm" method="POST" action="/contact">
<h1>Share your thoughts!</h1>
<p>Email</p>
<input id="email" name="email" placeholder="Type here your email" type="text"><br><br>
<p>Tell us what you think about us!</p>
<textarea id="content" name="content" class="contactarea" rows="10" placeholder="What would you like to talk about?"></textarea><br><br>
<button class="btn" id="submitBtn"> <i class="fas fa-sign-in-alt"></i>submit</button>
</form>
<script>
var button = document.getElementById('submitBtn');
button.addEventListener('click', function(e) {
// prevents the form from submitting
e.preventDefault();
emailValid();
// other validations you want to add
var form = document.findElementById('myForm');
form.submit();
});
</script>
Upvotes: 2
Reputation: 119
If you want to validate the email address in your HTML, you can do this:
<input id="email" name="email" onkeyup="emailValid()" placeholder="Type here your email" type="text">
<script>
function emailValid() {
var emailaddr = document.getElementById("email").value
if (emailaddr.includes("@gmail.com") !== true) {
emailaddr.value = "Invalid Email Address";
return false;
else {
return true;
}
}
</script>
To validate the email on submission, just call the emailValid() function in your script that runs on submission.
Upvotes: 2