So my code seems to work except the part where it writes to the database... It just keeps loading and if i press again it gives error 400. It does create users! I've looked everywhere but can't seem to find an answer
function register() {
const name = document.getElementById("usernameinput").value;
const email = document.getElementById("emailinput").value;
const password = document.getElementById("passinput").value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const userid = userCredential.user;
console.log(user);
update(ref(database, 'users/' + userid), {
username: name,
email: email,
Alfa: true,
Amstel: true,
Bavaria: true,
Brand: true,
Budels: true,
Dommelsch: true,
Gulpener: true,
Heineken: true,
HertogJan: true,
Jupiler: true,
Lindeboom: true,
Grolsch: true,
Leffe: true,
Desperados: true,
});
This is my form code:
<form class="register-form" id="registerform1">
<img src="src/IMG/profile.png" alt="profile">
<h1>Register</h1>
<input type="text" id="usernameinput" name="createUsername" placeholder="Username">
<input type="email" id="emailinput" value="" placeholder="example#example.com" name="createEmail">
<input type="password" id="passinput" value="" placeholder="password" name="createPass">
<button id="registerbutton" type="button">create</button>
<p class="message">Already registered? <a onclick="gotologin()">Sign In</a></p>
</form>
Fixed it!!!! user.id should've been user.uid! so the right code is:
const name = document.getElementById("usernameinput").value;
const email = document.getElementById("emailinput").value;
const password = document.getElementById("passinput").value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const useruid = userCredential.user.uid;
console.log(user);
update(ref(database, 'users/' + useruid), {
username: name,
email: email,
Alfa: true,
Amstel: true,
Bavaria: true,
Brand: true,
Budels: true,
Dommelsch: true,
Gulpener: true,
Heineken: true,
HertogJan: true,
Jupiler: true,
Lindeboom: true,
Grolsch: true,
Leffe: true,
Desperados: true,
});```
Related
I have some problems with mine Vue app.
I'm trying to validate login form that is connected with my Laravel App.
This is how template looks
<template>
<div>
<div class="main" v-if="canLogin">
<img class="logo" src="../assets/logo.png">
<form id="app"
#submit="checkForm"
method="post">
<p v-if="validation.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="validation in validation">{{ error }}</li>
</ul>
</p>
<input class="form-input" type="email" v-model="form.email" id="email" align="center" placeholder="eMail" required>
<input class="form-input" type="password" v-model="form.password" id="password" align="center" placeholder="Password" required>
<button #click.prevent="login" class="submit">Sign In</button>
</form>
</div>
<div class="main" v-if="!canLogin">
<span> YOU ARE BLOCKED FOR 15 MINUTES</span>
</div>
</div>
</template>
As you see I want to foreach errors, but it's always giving error that
'validation' is defined but never used
And this is how mine script looks.
<script>
import User from "../apis/User";
export default {
data() {
return {
form: {
email: "",
password: ""
},
validation: [],
errors: '',
message: '',
canLogin: true,
};
},
mounted() {
User.canLogin().then(response => {
this.canLogin = response.data.canLogin;
});
},
methods: {
checkForm: function (e) {
this.errors = [];
if (!this.form.password) {
this.errors.push("Name required.");
}
if (!this.form.email) {
this.errors.push('Email required.');
} else if (!this.validEmail(this.email)) {
this.errors.push('Valid email required.');
}
if (!this.errors.length) {
return true;
}
e.preventDefault();
},
validEmail: function (email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
},
login() {
User.login(this.form)
.then(response => {
this.$store.commit("LOGIN", true);
localStorage.setItem("token", response.data.token);
this.$router.push({ name: "Dashboard" });
this.$snotify.success(response.data.message, {
timeout: 2000,
showProgressBar: true,
closeOnClick: true,
pauseOnHover: true
});
})
.catch(error => {
if (error.response.status === 400) {
this.errors = error.response.data.message;
this.$snotify.error(error.response.data.message, {
timeout: 2000,
showProgressBar: true,
closeOnClick: true,
pauseOnHover: true
});
}
if(error.response.status === 429){
this.canLogin = false;
}
});
}
}
};
</script>
I'm catching few thhings, like, canLogin, this is checking if IP is not blocked.
There is one more error like:
Elements in iteration expect to have 'v-bind:key' directives
I'm just a started with vue so don't judge me if it's simple fix.
BTW: without validation works fine, I believe it's not only problem with those errors and probbly I'm not catching some things as needed.
What am I doing wrong here?
Change
<ul>
<li v-for="validation in validation">{{ error }}</li>
</ul>
To:
<ul>
<li v-for="(error,index) in errors" v-bind:key="index">{{ error }}</li>
</ul>
In vue, you must provide a key for every v-for looping.
And change your data to:
data() {
return {
form: {
email: "",
password: ""
},
validation: [],
errors: [],
message: '',
canLogin: true,
};
},
I made your errors variable an arrayList.
as this is my first question on StackOverflow, I do hope I provide you with enough details to the problem in order to fix it. If you need any further info, don't hesitate to ask.
In short, I'm trying to create a simple signup page for a newsletter that adds subscribers to Mailchimp.
In the terminal/command-line I get this message:
{
type: 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
title: 'Invalid Resource',
status: 400,
detail: "The resource submitted could not be validated. For field-specific details, see the 'errors' array.",
instance: '4d92a5b7-20fb-4f1c-be19-fbcd6548e745',
errors: [
{
field: '',
message: 'Required fields were not provided: email_address'
}
]
}
My HTML-body looks like this:
`
<img class="mb-4" src="images/logo.png" alt="" width="172" height="172">
<h1 class="h3 mb-3 font-weight-normal">Signup to our Newsletter</h1>
<input type="text" name="fName" class="form-control top" placeholder="First Name" required autofocus>
<input type="text" name="lName" class="form-control middle" placeholder="Last Name" required>
<input type="email" name="email" class="form-control bottom" placeholder="Email" required>
<button class="btn btn-lg btn-primary btn-block btn-sign-up" type="submit">Sign me up!</button>
<p class="mt-5 mb-3 text-muted">© PB Plus 2017-2020</p>
`
This is the 'POST' part of my Javascript:
app.post("/", function(req, res) {
const firstName = req.body.fName;
const lastName = req.body.lName;
const mail = req.body.email;
const data = {
members: [{
email_adress: mail,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
};
var jsonData = JSON.stringify(data);
const url = "https://us4.api.mailchimp.com/3.0/lists/fae76eccaf";
const options = {
method: "POST",
auth: "xavier1:6cbb8e0a03109b3b2ef74adc0127f986-us4"
}
const request = https.request(url, options, function(response) {
if (response.statusCode === 200) {
res.sendFile(__dirname + "/succes.html");
} else {
res.sendFile(__dirname + "/failure.html");
}
response.on("data", function(data) {
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
})
If anyone knows what I did wrong, please let me know! Thanks in advance.
Well, After spending many hours figuring out what's wrong, I typed email_adress instead of email_address. Problem solved.
I have a register form which works with Vue and local storage, when I submit the form blank or leave out an input the data is going to the local storage the same and not showing the HTML validation which is used by adding required attribute. Is there any way I can fix this problem by showing the HTML validation if the form has inputs which are empty or if the email do not have an at-sign inserted.
Form:
<form id="signup" method="post" v-on:submit.prevent>
<br>
<h1>Registration</h1>
<label for ="studentsorparents">Student or parents:</label>
<input type="text" id="studentsorparents" v-model="studentsorparents" required ="required">
<br><br>
<label for ="username">username:</label>
<input type="text" id="username" v-model="username" required ="required" v-text="null">
<br><br>
<label for="email">email: </label>
<input type="email" id="email" v-model='email' required ="required">
<br><br>
<label for="password">password: </label>
<input type="password" id="password" v-model='password' required ="required">
<br><br>
<button v-on:click='onSubmit' onclick="passuseremail()" >Register</button>
</form>
JS:
var signupApp = new Vue({
el: '#signup',
data: {
studentsorparents: '',
username: '',
email: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var studentParent = this.studentsorparents;
var newUser = this.username;
var newEmail = this.email;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser
})) {
alert('Account already exits');
return;
}
if (users) {
if (users.some(function (user) {
return user.email === newEmail
})) {
alert('Account already exits');
return;
} else {
alert('Account created');
window.location.href = 'user-profile.html' + '#' + newUser;
}
}
users.push({
'studentsorparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
});
localStorage.setItem('users', JSON.stringify(users));
} else {
users = [{
'studentparents': studentParent,
'username': newUser,
'email': newEmail,
'password': this.password
}];
localStorage.setItem('users', JSON.stringify(users));
}
}
}
});
function passuseremail()
{
var username = document.getElementById('username').value;
localStorage.setItem("user-check", username);
var studentsorparents=document.getElementById('studentsorparents').value;
localStorage.setItem("students-parents-check", studentsorparents)
var email=document.getElementById('email').value;
localStorage.setItem("email-check", email)
return false
}
You need to add button type='submit' to the submit button else it will behave like just any other button.
<button v-on:click='onSubmit' onclick="passuseremail()" type="submit">Register</button>
It then only act as submit button else it will just trigger the button eventlisteners attached.
You have spaces after required attributes in your inputs:
required ="required"
It's incorrect and it will not work; just write it like this:
<input type=email id=email v-model=email required>
You can validate email like this:
const email_re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
if (email_re.test( email.value )) {
/* email is valid */
} else {
/* email is not valid */
}
You can add a class to the button like jsValidateRegister.
And the add the code
First declare a variable
isPageValid = true
Then in add the following code for validation so the isPageValid is set to false inside the passuseremail();
$(".jsValidateRegister").click(function ()
{
passuseremail();
});
In the onSubmit: function () check
isPageValid === true
I want to show success message on my single post. I am using connect-flash, express-session to show the flash message.
Tried to flash the message in different page too. But, the message is not casting. So, it's not showing at any pages. I am following the scotch to show the success message.
When i am trying to submit blank the form, it shows the following error in console MongoError: E11000 duplicate key error collection
schema:
const eventSchema = new Schema({
name: {
type: String,
require: [true, 'Event name is required']
},
slug: {
type: String,
unique: true,
sparse: true
},
description: {
type: String,
require: [true, 'Event description is required']
},
}, {collection: 'event'});
const eventModel = mongoose.model('Event', eventSchema);
app.js:
const session = require('express-session'),
flash = require('connect-flash');
app.use(session({
secret: 'secret-key',
cookie: {
secure: true,
maxAge: 60000,
},
resave: false,
saveUninitialized: false
}));
app.use(flash());app.use(session({
secret: 'secret-key',
cookie: {
secure: true,
maxAge: 60000,
},
resave: false,
saveUninitialized: false
}));
app.use(flash());
controller:
const Event = require('../models/event'),
{ body, validationResult } = require('express-validator');
exports.showSingleEvent = async(req, res) => {
try {
await Event.findOne({ slug: req.params.slug }).exec((error, event) => {
if(error) {
res.status(404);
res.send('Events not found');
}
res.render('pages/single', {
title: `Event: ${event.name}`,
event: event,
success: req.flash('success')
});
});
} catch (error) {
return next(error);
}
};
exports.createEvent = ([
// Validate data
body('name')
.isLength({ min: 5, max: 30 })
.not().isEmpty()
.trim()
.escape(),
body('description')
.isLength({ min: 5, max: 200 }).withMessage('Must be between 5 & 200')
.not().isEmpty()
.trim()
.escape()
], async(req, res) => {
// Check if has errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
const event = new Event({
name: req.body.name,
description: req.body.description
});
await event.save((error) => {
if(error) throw error;
// Flash successful message
req.flash('success', 'Data has created successfully!');
// Redirect to newly created event
res.redirect(`/events/${event.slug}`);
});
}
});
single.ejs:
<% if (success.length > 0) { %>
<div class="alert alert-success mt-2 mb-2">
<%= success %>
</div>
<% } %>
<div class="jumbotron text-center">
<h1><%= event.name %></h1>
<p><%= event.description %></p>
<p>
All events
</p>
</div>
create.ejs:
<% if (errors.length > 0) { %>
<div class="alert alert-success mt-2 mb-2">
<% for (error of errors ) { %>
<%= error %> <br>
<% } %>
</div>
<% } %>
<form action="/events/create" method="POST">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" rows="5" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg">Create</button>
</div>
</form>
In my application, i have a html form to add user. Once user is added they will get mail using sendmail() function in javascript. Everything works fine and mail is sending as my standard. But i want to add the user name in the content of my email message.
example:
DEAR {USERNAME}
(follwed by my message)
HTML form is:
<form id="frmAddUser" method="post" action="/add_value" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="focusedInput">First Name</label>
<div class="controls">
<input class="input-xlarge focused" name="txtFirstName" type="text" id="txtFirstName" tabindex="2">
</div>
</div>
<div class="control-group">
<label class="control-label" for="focusedInput">Last Name</label>
<div class="controls">
<input class="input-xlarge focused" name="txtLastName" type="text" id="txtLastName" tabindex="3">
</div>
</div>
<div class="form-actions">
<input id="btnSubmit" class="btn btn-primary" value="Add User" onclick="return validateControls(this.form);" type="submit" />
<input id="btnCancel" class="btn" value="Clear" onclick="document.getElementById('tsubmit').style.display='none'; document.getElementById('loadeux').style.display=''; return true;" type="submit" />
</div>
</form>
And my js is like this:
exports.InsertData = function (req, res) {
var timestamp = new Date();
console.log(timestamp);
obj._id = req.body.txtLoginId,
obj.name = { f: req.body.txtFirstName, l: req.body.txtLastName },
obj.email = req.body.txtEmailID,
obj.MobileNo = req.body.txtmobile,
obj.Phone_Ext = req.body.txtphone,
obj.status = req.body.ddSfk,
obj.isAdmin = req.body.ddlAdmin,
obj.pwd = generatePassword(8),
obj.ispwdChange = "False",
obj.stamps = {
ins: timestamp,
Ins_Ip: ipAddress()
},
qry.insert(obj.schUserData, obj, function (err, result) {
if (err)
return;
sendMail(result.email, DbConfig.mailConfig.subject,'Dear{{{user}}}, Welcome to Bigtree Entertainment Pvt Ltd, Your Login details are below: your user name is: {{{user}}} and Password is: '+ result.pwd)
});
res.redirect('/Group');
}
///*----------- User Send Mail ---------------*/
function sendMail(toMailId, subject, body) {
for (var i = 0; i < 1; i++) {
email.send({
ssl: true,
host: DbConfig.mailConfig.host, // smtp server hostname
port: DbConfig.mailConfig.port, // smtp server port
domain: DbConfig.mailConfig.domain, // domain used by client to identify itself to server
to: toMailId,
from: DbConfig.mailConfig.from,
subject: subject,
reply_to: DbConfig.mailConfig.reply_to,
body: body,
authentication: DbConfig.mailConfig.authentication, // auth login is supported; anything else is no auth
username: DbConfig.mailConfig.username, // username
password: DbConfig.mailConfig.password, // password
debug: DbConfig.mailConfig.debug // log level per message
},
function (err, result) {
if (err) { console.log(err); }
});
}
}
My Json is:
{
"mongodbUrl":"mongodb://sfk:sfk#192.168.3.115:27017/BMS",
"mailConfig" :{
"host": "smtp.gmail.com",
"port": 465,
"domain": "[127.0.0.1]",
"from":"example#gmail.com" ,
"subject":"Please Use this Onetime password to create your own password",
"reply_to": "example#gmail.com",
"authentication": "login",
"username": "example#gmail.com",
"password": "paswd",
"debug": true
}
}