How to make a simple webpage register form using cookies? (jQuery) - javascript

I'm making a register/login form in javascript. User should enter information about himself and the computer should put that information into an array and remember it but it 'forgets' it every time I reload the page.
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
...more code
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
Any ideas to solve this? I have one more question. How can I check weather is an username alerady in use?
Here is the full js code:
var main = function() {
var people = [];
var cookies = [];
$('#register_email').val("");
$('#register_username').val("");
$('#register_password').val("");
$('#register2_password').val("");
function Person(username, email, password, repeat_password) {
this.username = username;
this.email = email;
this.password = password;
this.repeat_password = repeat_password;
}
$('#register').click(function() {
var username = $('#register_username').val();
var email = $('#register_email').val();
var password = $('#register_password').val();
var r_password = $('#register2_password').val();
if( email==="" || username==="" || password==="" || r_password==="") {
$('#error').text("You didn't fill everything");
}
else {
people[people.length] = new Person(username, email, password, r_password);
for(var key in people) {
//This should check weather this username was used before but I'm not really sure what to insert instead of "name"
if(people[people.length - 1].username === "name") {
$('#error').text("This username is already in use");
break;
}
else if(password !== r_password) {
$('#error').text("Passwords don't match");
break;
}
else {
document.cookie = email;
cookies[cookies.length] = document.cookie;
$('#error').text("Your registration is complete.");
break;
}
}
}
});
$('.btn').click(function() {
alert(cookies[cookies.length - 1]);
});
};
$(document).ready(main);
There is a js-fiddle live example in comments.

Related

JS problem when creating a Class Function that is gonna validate name by calling function inside the Class

So this is my code: pressing a button creates html mssg:
Inside the class Student, I tried to check names for inv characters and empty fields.
Then I wanted to pass through another f-on which would check if both f-ons doing their thing and to call her outside the class.
I tried different ways to solve it but returns the same result.
Please if someone knows to resolve or explain in more details would be grateful.
TY all.
constructor(fullName, address, phone, course) {
this._fullName = fullName;
this.address = address;
this.phone = phone;
this.course = course;
}
validateName(text) {
let regex = /^[A-Za-z0-9 ]+$/;
let isValid = regex.test(text);
if (!isValid) {
alert("Contains Special characters");
} else {
alert("OK");
}
}
checkName(text) {
text = text.trim();
if (text === "") {
throw new Error("The name can not be empty");
} else {
return (this._fullName = text);
}
}
sucess(text) {
let notChars = this.validateName(text);
let notEmpty = this.checkName(text);
if (!notChars || !notEmpty) {
return alert("chars or empty");
} else {
return alert("ok");
}
}
getInfo() {
return `Name: ${this._fullName} <br> Address: ${this.address}<br> Phone: ${this.phone}<br> Course: ${this.course}`;
}
}
let fullName = $("#fullName");
let address1 = $("#inputAddress");
let address2 = $("#inputAddress2");
let inputCity = $("#inputCity");
let inputZip = $("#inputZip");
let phone = $("#phoneNumber");
let show = $("#show");
let course = $("#course");
$("#signInBtn").on("click", (e) => {
e.preventDefault();
let address = `${address1.val()} ${address2.val()} ${inputCity.val()} ${inputZip.val()}`;
let student1 = new Student(
fullName.val(),
address,
phone.val(),
course.val()
);
show.html(student1.sucess("Steva"));
});

How do I add an email cc into my Google Script

I have a Google Script that I've inherited and I'm looking to update it to reflect current requirements.
Currently it fires off 2 emails to a participant and sponsor using data in a Google Sheet. I've tried combining it so that section 'Now email for each doc' sends an email to the participant and cc's the sponsor.
I've gotten as far as updating the code from :
var sendTo = row[EMAIL];
to :
var sendTo = row[EMAIL] + " , " + sponsors;
and removing section '2. Personal Case' which doesn't solve the cc query.
I've tried amending the existing code to add in the additional parameters as stated on https://developers.google.com/apps-script/reference/mail/mail-app but can't seem to get it to work in the code below.
// Now email for each doc
var email = getAppraiseeEmail();
if(email && email.body) {
email.body = email.body.replaceAll('%doctitle1%', bTitle)
/*.replaceAll('%doctitle2%', pTitle)
.replaceAll('%doctitle3%', dTitle)
.replaceAll('%doctitle4%', dpTitle)
.replaceAll('%link1%', bFile.getUrl())
.replaceAll('%link2%', pFile.getUrl())
.replaceAll('%link3%', dFile.getUrl())
.replaceAll('%link4%', dpFile.getUrl())*/
.replaceAll('%link5%', child.getUrl())
.replaceAll('%name%', row[NAME]);
var sendTo = row[EMAIL];
if(sendTo && sendTo!=='') {
email.recipient = sendTo;
sendAnEmail(email);
}
} else {
throw Error('missing email configuration (Business Case)');
}
// 2. Personal Case
if(sponsors.length > 0) {
var emailRev = getSponsorEmail();
if(emailRev && emailRev.body) {
emailRev.body = emailRev.body.replaceAll('%doctitle1%', bTitle)
/*.replaceAll('%doctitle2%', pTitle)
.replaceAll('%doctitle3%', dTitle)
.replaceAll('%doctitle4%', dpTitle)
.replaceAll('%link1%', bFile.getUrl())
.replaceAll('%link2%', pFile.getUrl())
.replaceAll('%link3%', dFile.getUrl())
.replaceAll('%link4%', dpFile.getUrl()) */
.replaceAll('%link5%', child.getUrl())
.replaceAll('%name%', row[NAME]);
var sendTo = sponsors.join(',');
if(sendTo && sendTo!=='') {
emailRev.recipient = sendTo;
sendAnEmail(emailRev);
}
} else {
throw Error('missing email configuration (sponsor)');
}
} // end if re sponsors
row[NOTES] = 'Files created & shared, ' + timestamp;
} catch(e) {
console.error(e);
row[NOTES] = 'An error occurred (' + e + '), ' + timestamp;
}
function getAppraiseeEmail() {
var email = {};
email.body = getConfig('email01');
email.subject = getConfig('subject01');
return email;
}
function getSponsorEmail() {
var email = {};
email.body = getConfig('email02');
email.subject = getConfig('subject02');
return email;
}
function sendAnEmail(email) {
var options = { noReply: true, htmlBody: email.body };
MailApp.sendEmail(email.recipient, email.subject, null , options);
}
Ideally it should fire out the email from section 'Now email for each doc' and cc the sponsors in section '2. Personal Case'.
Thanks in advance!
UPDATE 15/07/19
I've updated the code to the below which now works:
// Now email for each doc
var email = getAppraiseeEmail();
if(email && email.body) {
email.body = email.body.replaceAll('%doctitle1%', bTitle)
.replaceAll('%link5%', child.getUrl())
.replaceAll('%name%', row[NAME]);
var CC = row[SPONSORS]
var sendTo = row[EMAIL]
if(sendTo && sendTo!=='') {
email.recipientTO = sendTo;
email.CC = CC;
sendAnEmail(email);
}
} else {
throw Error('missing email configuration (Business Case)');
}
row[NOTES] = 'Files created & shared, ' + timestamp;
} catch(e) {
console.error(e);
row[NOTES] = 'An error occurred (' + e + '), ' + timestamp;
}
function getAppraiseeEmail() {
var email = {};
email.body = getConfig('email01');
email.subject = getConfig('subject01');
return email;
}
function sendAnEmail(email) {
var options = { noReply: true, htmlBody: email.body, cc: email.CC };
MailApp.sendEmail(email.recipientTO, email.subject, null , options);
}

How to persist data in an array even when the page reloads, using javascript?

I have created a register and a login form using html and javascript. Where I am storing the user data in an array and then in local storage. For this I have initially declared an empty array called var users=[];
Thus, when the page reloads the previously stored data is lost as array becomes empty again and data in the local storage is overwritten. Please help, on how to avoid the array become empty after reloading the page.
Following is my controller.js-
//Declaring an empty array
var users = [];
//Setting id for each users
var idInput = makeCounter();
//Fetching data from textboxes in register.html
var firstnameInput = document.getElementById("firstname");
var lastnameInput = document.getElementById("lastname");
var emailInput = document.getElementById("email");
var usernameInput = document.getElementById("username");
var passwordInput = document.getElementById("password");
var dobInput = document.getElementById("dob");
var messageBox = document.getElementById("editeddata");
//Declaring custom constructor function
function userdetails(id, firstname, lastname, email, dob, username, password){
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.dob = dob;
this.username = username;
this.password = password;
this.FullName = this.firstname +' ' + this.lastname;
}
//counter funtion, to fetch user id
function makeCounter() {
var arraylength=users.length;
return function(){
return arraylength+1;
}
}
//insert data while registration
function registerUser()
{
//Email validation
var emailinput = document.forms["myform"]["email"].value;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!(emailinput).match(emailReg) || emailinput=="")
{
alert("Not a valid e-mail address");
return false;
}
//check, if fields are empty
if(firstnameInput.value=="" || lastnameInput.value=="" || passwordInput.value=="" || dobInput.value=="")
{
alert("Fields cannot be empty");
return false;
}
//check, if a user already exist
var usernameinput = document.forms["myform"]["username"].value;
var passwordinput = document.forms["myform"]["password"].value;
var ulen= users.length;
for(i=0; i < ulen; i++)
{
if ( usernameinput == users[i].username && passwordinput == users[i].password)
{
alert("User already exists");
return false;
}
}
var user=new userdetails(idInput(),firstnameInput.value, lastnameInput.value, emailInput.value, dobInput.value, usernameInput.value, passwordInput.value);
users.push(user);
alert("Registered successfully");
localStorage.setItem("key_users", JSON.stringify(users));
}
You can use local storage value at the time of initialisation.
if (typeof(Storage) !== "undefined") {
if (localStorage.key_users) {
users = localStorage.key_users;
} else {
users = [];
}
}
you can use something like this to check if the key is already in localStorage or not.
<html>
<head>
<link href="style.css" rel="stylesheet">
</head>
<body onload="test()">
<script>
function test(){
var value = (localStorage.getItem("key1"))
console.log(value)
if(value == null){
localStorage.setItem("key1","value1")
alert("Hellow")
}else{
var value=localStorage.getItem("key1");
alert(value)
}
}
</script>
</body>
</html>

how to compare the value

This my code
I am getting email address from database through ajax and mysql it is giving me value in . so in below FUNCTION comparing() i am retriving data from span to compare with the textfield data. but it is not comparing properly.
Please help me out
function validate(pageForm)
{
/************Getting error values in return values***********************/
var returncomparing = "";
/*********************************/
//FIELD WHICH YOU HAVE TO VALDATE
returncomparing += comparing(pageForm.email);
/********************************************/
if (returncomparing != "")
{
document.getElementById('error').innerHTML = returnIndustry;
}
return false;
}
After giving correct EMAIL still it is giving Error ... (Please Provide Login User ID)
function comparing(pageForm){
var error = "";
// var fetchedEmail=document.forms["pageForm"]["email_fetch"].value;
var em=document.forms["pageForm"]["email"].value;
//var emai = document.getElementById('emlTst').value;
var email = document.getElementById('txtHint').innerHTML;
//document.getElementById('emlTst').value = email;
if(em != email){
document.getElementById('error_email2').innerHTML="Please Provide Login User ID";
pageForm.style.borderColor = 'red';
error='5';
}
else if(em == email){
document.getElementById('error_email2').innerHTML="";
error = "";
}
else {
document.getElementById('error_email2').innerHTML="";
pageForm.style.borderColor = '#c7c7c7';
}
return error;
}
/*************************************************************/
var em = $('#email').val().toLowerCase();
var email = $('#txtHint').val().toLowerCase();

Creating a login in javascript - array comparison

I have a login box using a simple javascript login comparing usernames and passwords, before you all start I know about the security issues in using javascript for authentication. Here is the code
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = false;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters", "Jonathan Goss", "Lisa Cain", "Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
document.getElementById("mandatory1").value = un;
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
At the moment if the login is successful I'm posting the username to a hidden field which is then being used by a piece of a software. How do I associate the names in fnArray with the other correct username & password so that I can then grab associated full name and post that to the hidden field "mandator1" instead?
You can get the index of the correct user
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters, Jonathan Goss, Lisa Cain, Jenny Dempsey"];
var index = 0;
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
index = i;
break;
}
}
now you can access the correct data using
unArray[index];
// and so on for other arrays
Define a variable for full name, and set it if you have the valid user:
var fn = "";
/* ... */
valid = true;
fn = fnArray[i];
/* ... */
document.getElementById("mandatory1").value = fn;
Note: Actually you can check validity later on using fn. If it is empty string, then no user was logged in. This makes it have same purpose as valid, and more.
Try this.
function validate() {
var un = document.getElementById("usern").value;
var pw = document.getElementById("pword").value;
var valid = -1;
var unArray = ["markwalt", "jongossy", "lisacain", "jenndemp"];
var pwArray = ["mark1234", "flomaygo", "lisa1234", "jenny1234"];
var fnArray = ["Mark Walters","Jonathan Goss","Lisa Cain","Jenny Dempsey"];
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = i;
break;
}
}
if (valid != -1) {
alert ("Login was successful");
document.getElementById("mandatory1").value = fnArray[valid];
}
else {
alert("Invalid Username and/or Password! Please try again. You will not be able to submit this form without a successful login")
document.getElementById("pword").value = "";
document.getElementById("usern").value = "";
document.getElementById("usern").focus();
}
}
set mandatory1 when the login is successful based on i (in the for loop)

Categories

Resources