form validation + json parse - javascript

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>

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>

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.

Related

How to have my input value appear in all my html pages?

I am storing the username and password in an array(datas),,then after registering and logging in, I am only able to have the username appear in the login page.. How can i make the username appear in all of my html pages?Like storing it in a session variable so i could have the username in all of my other pages. Thank you!
<script>
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(e) {
e.preventDefault();
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
var found_user = datas.find(d => d.username === username && d.password === password);
if (found_user) {
document.getElementsByClassName('loguser')[0].innerHTML = found_user.username;
}
}
document.getElementById("login_button").addEventListener("click", isUserValid);
</script>
<body>
<div class="loguser">
User
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" id="login_button" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
You can use your browser's localstorage to store the values and retrieve them on other pages. Another option would be to use cookies, but I believe this would be a little more complicated.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Here's the documentation that talks a little more about. I think this will help you =)
An important point is that this will be saved in the user's browser, if you need this data, I recommend using a database
Use localStorage, is really simple. To set the value use this:
window.localStorage.setItem('actualUserName', document.getElementById('lusername').value);
And to retrieve the value use this:
window.localStorage.getItem('actualUserName');
More info: https://developer.mozilla.org/es/docs/Web/API/Window/localStorage

How to append and save form data to txt file using javascript

I have this html code:
<form action="" method="post" id="formToSave">
<h1>Subscribe For Latest Blogs</h1>
<p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p>
<div class="email-box">
<i class="fas fa-envelope"></i>
<input class="tbox" type="email" name="email" id ="email" value="" placeholder="Enter Your Email Address">
<m><button class="btn" type="submit" name="button" onclick="saveFile()" >Subscribe</button></m>
</div>
</form>
And also have this javascript code:
<script>
let saveFile = () => {
const email = document.getElementById('email');
let data = email.value;
const textToBLOB = new Blob([data], { type: 'text/plain' });
}
</script>
I want to save the email address form data to a text file and append further email addresses to that file. what should I do next?
First of all, i recommend doing this in a server because browser javascript doesn't have access to the file system and cannot append new text into a file. However, if you need a text file with the emails given by only one client, the following code might help. Keep in mind that this will only work on the client's side and it wont help for a subscribe system without a server.
const emailsList = []
function addEmailToList() {
const email = document.getElementById('email')
const { value } = email
emailsList.push(value)
}
function downloadFile() {
const textFile = btoa(emailsList.join('\n'))
const saveElement = document.createElement('a')
saveElement.href = `data:text/plain;base64,${textFile}`
saveElement.download = 'myList.txt'
document.body.appendChild(saveElement)
saveElement.click()
document.body.removeChild(saveElement)
}
<form action="" method="post" id="formToSave">
<h1>Subscribe For Latest Blogs</h1>
<p>Please subscribe in my website using your email address for latest updates about my blogs and publications.</p>
<div class="email-box">
<i class="fas fa-envelope"></i>
<input class="tbox" type="email" name="email" id="email" value="" placeholder="Enter Your Email Address" />
<m><button class="btn" type="button" name="button" onclick="addEmailToList()">Subscribe</button></m>
<m><button class="btn" type="button" name="button" onclick="downloadFile()">Download TextFile</button></m>
</div>
</form>

I have this form, and I cant get it it to get validated

I have this form and it needs to be validated. For example, no numbers in the name field, and Message part can't be more than 200 characters. I have tried writing JavaScript code but it doesn't just work.
<aside id="sidebar">
<div class="dark">
<form id="quote" >
<h3>Get A Quote</h3>
<div>
<label>Name</label><br>
<input type="text" placeholder="Name">
</div>
<div>
<label>Email</label><br>
<input type="email" placeholder="Email Address">
</div>
<div>
<label>Message</label><br>
<textarea placeholder="Message"></textarea>
</div>
<button class="button_1" type="submit">Send</button>
</form>
</div>
</aside>
I expect for it also to say if a part is not filled but I can't get it to work.
You can validate which name accepts only text and spaces you can use this expression /^[a-zA-Z\s]+$/ read about it in this answer https://stackoverflow.com/a/12778207/615274. Validating the message is a little simpler. It is possible to define the maximum number of characters to accept in textarea using maxlength attribute. This possibility can prevent you from writing code. Please look at the following example
const form = document.forms.form;
form.addEventListener('submit', handleSubmit, true);
function handleSubmit(event) {
event.preventDefault();
const name = this.name.value;
const message = this.message.value;
if (!isValidName(name)) {
alert('Not valid name!');
return false;
}
if (!isValidMessage(message)) {
alert('Not valid message!');
return false;
}
this.submit();
}
function isValidName(name) {
// const expresion = /^[A-Za-z]+$/;
const expresion = /^[a-zA-Z\s]+$/;
return expresion.test(name);
}
function isValidMessage(message) {
if (message.length > 200) {
return false;
}
return true;
}
<form action="#" name="form">
<h3>Get A Quote</h3>
<div>
<label>Name</label><br>
<input type="text" id="name" name="name" placeholder="Name">
</div>
<div>
<label>Email</label><br>
<input type="email" placeholder="Email Address">
</div>
<div>
<label>Message</label><br>
<textarea id="message" name="message" minlength="1" maxlength="200" placeholder="Message"></textarea>
</div>
<button class="button_1" type="submit">Send</button>
</form>
The link provided by Andreas is definitely your friend for this issue.
For your specific needs, you want "required", maxlength="200", and (I think) "pattern='^\D+$'".
You can use the pattern attribute for this and on js side use checkValidity() to check if the input is valid or not.
$('#name').on('keyup', (ev) => {
var isValid = $('#name')[0].checkValidity();
$('span').html(isValid ? 'yes': 'no');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" placeholder="Name" pattern="[a-zA-Z]*">
<div>isValid: <span></span></div>

How to Validate an Email Submission Form When There Are Multiple on the Same Page Using the Same Class?

I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>

javascript validation not happening

I have written the following form in my html file.
<form name = "myForm" method="post" action="" id="comment_form" class="comment_form" onsubmit="return validateForm()" >{% csrf_token %}
<div class="row-fluid">
<div class="span6">
<input type="text" id="email" name="email" placeholder="Email*">
</div>
<div class="span6">
<input type="text" id="name" name="name" placeholder="Name*">
</div>
</div>
<div class="row-fluid">
<div class="span8">
<textarea name="message" id="txt_message" placeholder="Message*" cols="30" rows="10"></textarea>
</div>
<div class="span4">
<button class="btn " type="button"><i class="li_paperplane"></i>Send message</button>
</div>
</div>
</form>
And I have added this javascript function inside my HTML file
<script>function validateForm()
{
var x=document.forms["myForm"]["name"].value;
var y=document.forms["myForm"]["email"].value;
var a=document.forms["myForm"]["message"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (x==null || x=="" ||y==null||y==""||a==""||a==null)
{
alert("All fields must be filled out");
return false;}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Please enter a valid e-mail address");
return false;
}
else{
alert("Thank you for your response");
return true;
}
}</script>
On click of Send Message button I am not getting any response from the javascript. The code looks fine and the same code is working on another HTML file. What seems to be the problem?
Your "Send Message" button is just a button -- it doesn't submit the form. You can either use an <input type="submit"> or use JavaScript on your <button> to submit the form.
You need to add an onclick event to your button. Add the following attribute to the button
Syntax:
onclick="document.NameOfTheForm.submit();"
So in this syntax you have to add following
onclick="document.myForm.submit();"

Categories