when i save to my database i don't receive my data - javascript

when i input data in the form to get Smtp, according to my code am to get the data and save it to my database but its not working, i don't receive any data info in my mongodb, i only get the Date
this is what my database looks like
my view(ejs)
<h1 class="mt-4">Dashboard</h1>
<div class="row mt-5">
<div class="col-md-6 m-auto">
<div class="card card-body">
<h1 class="text-center mb-3">
<i class="fas fa-user-plus"></i> Add Smtp
</h1>
<% include ./partials/messages %>
<form action="/users/mail" method="POST">
<div class="form-group">
<label for="smtpUsername">smtpUsername</label>
<input
type="name"
id="smtpUsername"
name="smtpUsername"
class="form-control"
placeholder="Enter smtpUsername"
value="<%= typeof smtpUsername != 'undefined' ? smtpUsername : '' %>"
/>
</div>
<div class="form-group">
<label for="smtpPassword">smtpPassword</label>
<input
type="name"
id="smtpPassword"
name="smtpPassword"
class="form-control"
placeholder="Enter smtpPassword"
value="<%= typeof smtpPassword != 'undefined' ? smtpPassword : '' %>"
/>
</div>
<div class="form-group">
<label for="smtpUrl">smtpUrl</label>
<input
type="name"
id="smtpUrl"
name="smtpUrl"
class="form-control"
placeholder="Enter smtpUrl"
value="<%= typeof smtpUrl != 'undefined' ? smtpUrl : '' %>"
/>
</div>
<button type="submit" class="btn btn-primary btn-block">
Add Smtp
</button>
</form>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-md-6 m-auto">
<div class="card card-body">
<h1 class="text-center mb-3">
<i class="fas fa-user-plus"></i> send mail
</h1>
<% include ./partials/messages %>
<form action="/users/mail" method="POST">
<div class="form-group">
<label for="to">to</label>
<input
type="name"
id="to"
name="to"
class="form-control"
placeholder="Enter to"
value="<%= typeof to != 'undefined' ? to : '' %>"
/>
</div>
<div class="form-group">
<label for="bcc">bcc</label>
<input
type="name"
id="bcc"
name="bcc"
class="form-control"
placeholder="Enter bcc"
value="<%= typeof bcc != 'undefined' ? bcc : '' %>"
/>
</div>
<div class="form-group">
<label for="cc">cc</label>
<input
type="name"
id="cc"
name="name"
class="form-control"
placeholder="Enter cc"
value="<%= typeof cc != 'undefined' ? cc : '' %>"
/>
</div>
<div class="form-group">
<label for="subject">subject</label>
<input
type="name"
id="subject"
name="subject"
class="form-control"
placeholder="Enter subject"
value="<%= typeof subject != 'undefined' ? subject : '' %>"
/>
</div>
<div class="form-group">
<label for="message">message</label>
<input
type="name"
id="message"
name="message"
class="form-control"
placeholder="Enter message"
value="<%= typeof message != 'undefined' ? message : '' %>"
/>
</div>
<button type="submit" class="btn btn-primary btn-block">
Register
</button>
</form>
</div>
</div>
</div>
Logout
when i input data in the form to get Smtp, according to my code am to get the data and save it to my database but its not working, i don't receive any data info in my mongodb, i only get the Date
my schema
const mongoose = require('mongoose');
const MailSchema = new mongoose.Schema({
to: {
type: String,
},
cc: {
type: String,
},
bcc: {
type: String,
},
subject: {
type: String,
},
message: {
type: String,
},
attachment: {
type: String,
},
date: {
type: Date,
default: Date.now
},
});
const SmtpSchema = new mongoose.Schema({
smtpUrl: {
type: String,
required: true
},
smtpUsername: {
type: String,
required: true
},
smtpPassword: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
});
const Mail = mongoose.model('Mail', MailSchema);
const Smtp = mongoose.model('Smtp', SmtpSchema);
module.exports = Mail;
when i input data in the form to get Smtp, according to my code am to get the data and save it to my database but its not working, i don't receive any data info in my mongodb, i only get the Date
my Route
router.get('/mail', forwardAuthenticated, (req, res) =>
res.render('mail', {
user: req.user,
mail: req.mail
})
);
router.post('/mail', (req, res) => {
const { to, cc, bcc, subject, message, attachment } = req.body;
const { smtpUrl, smtpUsername, smtpPassword } = req.body;
console.log(smtpUrl)
console.log(smtpPassword)
console.log(smtpUsername)
let errors = [];
if (!smtpUrl || !smtpUsername || !smtpPassword) {
errors.push({ msg: 'Add an account' });
res.render('mail', {
smtpUrl,
smtpPassword,
smtpUsername
});
}else{
console.log(smtpUrl)
console.log(smtpPassword)
console.log(smtpUsername)
const newSmtp = new Smtp({
smtpUrl,
smtpPassword,
smtpUsername
});
newSmtp
.save()
.then(mail => {
req.flash(
'success_msg',
'Account Added'
);
})
.catch(err => console.log(err));
}
if (!to || !subject || !message) {
errors.push({ msg: 'Please enter all fields' });
}
if (errors.length > 0) {
res.render('mail', {
errors,
to,
cc,
bcc,
subject,
message,
attachment,
});
} else {
const newMail = new Mail({
to,
cc,
bcc,
subject,
message,
attachment,
});
let transporter = nodemailer.createTransport({
service: smtpUrl,
auth: {
user: smtpUsername,
pass: smtpPassword
}
});
let mailOptions = {
from: smtpUsername,
to: to,
subject: subject,
text: `${message}`
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
newMail
.save()
.then(mail => {
req.flash(
'success_msg',
'mail sent'
);
})
.catch(err => console.log(err));
console.log('Email sent: ' + info.response);
}
});
}
})

Related

How do I send an action in Sails.js after getting form data?

Currently, I can get the form data from my html but the action isn't being triggered after the fact. I'm trying to signup a user but my signup action file never gets reached. After I click submit, I receive no errors, but the new user isn't created either.
Any helps appreciated. Thanks :)
signup.ejs
<h2>Please Sign up.</h2>
<div class="container">
<div class="signup-form">
<ajax-form class="ajax-form" action="signup" :handle-parsing="handleParsingForm">
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" type="text" :class="[formErrors.username
? 'is-invalid' : '']" v-model.trim="formData.username" placeholder="Sturgis P. Sturgeon"
autocomplete="name" focus-first>
<div class="invalid-feedback" v-if="formErrors.username">Please enter your full
name.</div>
</div>
<div class="form-group">
<label for="password">Choose a password</label>
<input class="form-control" id="password" type="password" :class=".
[formErrors.password ? 'is-invalid' : '']" v-model.trim="formData.password"
placeholder="••••••••" autocomplete="new-password">
<div class="invalid-feedback" v-if="formErrors.password">Please enter a password</div>
</div>
<div class="form-group">
<label for="confirm-password">Confirm password</label>
<input class="form-control" id="confirm-password" type="password" :class=".
[formErrors.confirmPassword ? 'is-invalid' : '']" v-model.trim="formData.confirmPassword"
placeholder="••••••••" autocomplete="new-password">
<div class="invalid-feedback" v-if="formErrors.confirmPassword">Your password
and confirmation do not match.</div>
</div>
<ajax-button type="submit" class="btn ajax-button" :class="[syncing ? 'syncing' :
'']">Submit</ajax-button>
</form>
</div>
</div>
</div>
Route
`"POST /signup": {action: 'signup'}`
Cloud Setup
`"signup":{
"verb":"POST","url":"/signup","args":["username","password"]
}`
handleParsingForm
`handleParsingForm: function() {
this.formErrors = {};
var argins = this.formData;
if(!argins.username) {
this.formErrors.username = true;
}
if(!argins.password) {
this.formErrors.password = true;
}
if(argins.password && argins.password !== argins.confirmPassword) {
this.formErrors.confirmPassword = true;
}
if (Object.keys(this.formErrors).length > 0) {
return;
}
return argins;
}
signup action
`signup: async function (inputs) {
const { username, password, confirmPassword } = inputs;
try {
let existingUser = await User.findOne({
username
})
if (existingUser) {
throw(400, 'That username is already taken.')
}
} catch (error) {
throw(error);
}
finally {
if (password === confirmPassword) {
let newUser = {username, password}
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password1, salt, (err, hash) => {
newUser.password = hash;
User.create(newUser);
});
})
// };
};
// this.req.session.userId = newUser.id;
// return newUser;
}`
The route should be
'POST /api/v1/signup': { action: 'signup' }
then rerun sails run rebuild-cloud-sdk

TypeError: res.response is undefined

I'm doing an user authentication using JWT auth in a SPA with Vue/Laravel. I have an issue with the register module, it isn't doing anything when I click the button, I checked Firefox developer edition's console and it throws me the following error:
TypeError: res.response is undefined
This is my code
<template>
<div class="container">
<div class="card card-default">
<div class="card-header">Inscription</div>
<div class="card-body">
<div class="alert alert-danger" v-if="has_error && !success">
<p v-if="error == 'registration_validation_error'">Error</p>
<p v-else>Try again later.</p>
</div>
<form autocomplete="off" #submit.prevent="register" v-if="!success" method="post">
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.email }">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control" placeholder="user#example.com" v-model="email">
<span class="help-block" v-if="has_error && errors.email">{{ errors.email }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password">Mot de passe</label>
<input type="password" id="password" class="form-control" v-model="password">
<span class="help-block" v-if="has_error && errors.password">{{ errors.password }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password_confirmation">Confirm password</label>
<input type="password" id="password_confirmation" class="form-control" v-model="password_confirmation">
</div> <button type="submit" class="btn btn-default" #click="register">Inscription</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
name: '',
email: '',
password: '',
password_confirmation: '',
has_error: false,
error: '',
errors: {},
success: false
}
},
methods: {
register() {
var app = this
this.$auth.register({
data: {
email: app.email,
password: app.password,
password_confirmation: app.password_confirmation
},
success: function () {
app.success = true
this.$router.push({
name: 'Login',
params: {
successRegistrationRedirect: true
}
})
},
error: function (res) {
console.log(res.response.data.errors)
app.has_error = true
app.error = res.response.data.error
app.errors = res.response.data.errors || {}
}
})
}
}
}
</script>
If this gives some sort of hint I also have this warning in console:
Reason: CORS request did not succeed
I have no idea why is this happening.
You're running into a CORS error which means that the server you're making a request to is not allowing requests from your client domain. If you own the server you'll need to add your domain to the list of allowed domains, or if this fails, check that the request method "POST" is allowed.
It looks like you're then getting the 'res.response" error as when the error gets caught in the error function, it's returning an error message which doesn't have a "response" property. Try console.log'ing the "res" response to see what it's giving you and adjust the property you're using from there.

Vuelidate errors return true but elements don't render

I have a contact form that uses vuelidate to validate fields. The problem is - the validation works, but the errors don't render.
$v.name.dirty is TRUE and $v.name.required is FALSE.
Logging $v.name.dirty && !$v.name.required returns TRUE which is the same condition in the v-if directive but the error elements still don't show.
However, when .$touch() is called and $v.name.dirty becomes true and $v.name.required false, anything I type in the input fields will show the errors.
JS:
import translationsBus from "../../app/translations";
export default {
name: "contactForm",
beforeMount() {
this.$store.dispatch("updateTranslations", translationsBus.translations);
},
data: function () {
return {
name: '',
email: '',
subject: '',
message: ' ',
errors: [],
isSuccessful: ''
}
},
mounted() {
var my_axios = axios.create({
baseURL: '/'
});
Vue.prototype.$http = my_axios;
},
computed: {
isLogged: function () {
return isLoggedOn;
},
shouldShowSubjectOption: function () {
return showSubjectOption;
},
translations: function () {
return this.$store.state.translations.translations;
},
},
methods: {
onContactUsClick: function onContactUsClick() {
const _this = this;
this.$v.$touch();
if (!this.$v.$error) {
let model = {
senderName: _this.name,
senderEmail: _this.email,
subject: _this.subject,
message: _this.message
};
this.$http.post('/home/contactus', model)
.then(response => {
console.log(response);
_this.isSuccessful = response.data;
})
.catch(e => {
console.log(e);
});
}
}
},
validations: {
email: {
required: required,
isValidEmail: function isValidEmail(value) {
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(value);
}
},
name: {
required: required
},
subject: {
required: required
},
message: {
required: required
}
}
}```
HTML:
<div v-bind:class="{ 'col-lg-6' : shouldShowSubjectOption, 'col-lg-12' : !shouldShowSubjectOption }">
<div id="form-contact">
<h1 class="lead">Get in touch...</h1>
<form class="text-center" >
<div class="form-group">
<label for="name">{{translations['contact_Form_Name']}}</label>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<input type="text" class="form-control" name="senderName" id="senderName" v-model:bind="name" v-bind:placeholder="translations['contact_Form_NamePlaceholder']" />
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.name.$dirty && !$v.name.required">{{translations['shared_Validation_ReuiredField']}}</label>
</div>
</div>
<div class="form-group">
<label for="email">{{translations['contact_Form_EmailAddress']}}</label>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-envelope"></span></span>
<input type="email" class="form-control" name="senderEmail" id="senderEmail" v-model:bind="email" v-bind:placeholder="translations['contact_Form_EmailAddressPlaceholder']" />
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.email.$dirty && !$v.email.required">{{translations['shared_Validation_ReuiredField']}}</label>
<label class="control-label" v-if="$v.email.$dirty && $v.email.required && !$v.email.isValidEmail">{{translations['contact_Form_EmailAddressValidationMessage']}}</label>
</div>
</div>
<div class="form-group" v-if="shouldShowSubjectOption">
<label for="subject">{{translations['contact_Form_Subject']}}</label>
<select id="subject" name="subject" class="form-control" v-model:bind="subject" v-bind:title="translations['contact_Form_SubjectPickerText']">
<option value="service">1</option>{{translations['contact_Form_SubjectOption_GCS']}}
<option value="suggestions">2</option>{{translations['contact_Form_SubjectOption_Suggestions']}}
<option value="product">3</option>{{translations['contact_Form_SubjectOption_ProductSupport']}}
</select>
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.subject.$dirty && !$v.subject.required" v-cloak>{{translations['shared_Validation_ReuiredField']}}</label>
</div>
<div class="form-group">
<label for="name">{{translations['contact_Form_Message']}}</label>
<textarea name="message" id="message" class="form-control" v-model:bind="message" rows="9" cols="25"
placeholder="">{{translations['contact_Form_Message']}}</textarea>
</div>
<div class="has-error" v-cloak>
<label class="control-label" v-if="$v.message.$dirty && !$v.message.required">{{translations['shared_Validation_ReuiredField']}}</label>
</div>
<div class="form-group" v-if="isLogged">
<div class="g-recaptcha" data-sitekey=""></div>
</div>
<button type="button" class="btn btn-primary btn-block" v-on:click="onContactUsClick" id="btnContactUs">{{translations['contact_Form_SendMessageButton']}}</button>
</form>
</div>
</div>
</div>
</div>
I expect error elements to appear on submit.

Sending a POST request using Request module but getting almost empty array of data

I'm trying to send a POST request to an API using the request module but when i console.log the data sent it seems only the time, approved status and id are sent which is by default from the model schema but the rest data are not sent. I need help.
This is what is sent
instead of something like this
console.log(req.body) when i send data with Postman
the request body when i send data with request module
let mongoose = require('mongoose');
//models config
let jobSchema = new mongoose.Schema({
title: String,
category: String,
description: String,
type: String,
url: String,
email: String,
apply: String,
location: String,
company: String,
// path: String,
approved: {type: Boolean, default: false},
created: {type: Date, default: Date.now, expires: 1000}
})
let Job = mongoose.model('Job', jobSchema);
module.exports = Job;
//This is from another file :helpers
exports.createJob = (req, res) => {
db.Job.create(req.body)
.then((newJob) => {
res.status(201).json(newJob)
})
.catch((err) => {
res.send(err)
})
}
//post
app.get('/jobs/add', (req, res) => {
res.render('add')
})
app.post('/jobs', (req, res)=>{
// let formBody = {
// title: req.title,
// category: req.category,
// description: req.body.description,
// type: req.body.type,
// url: req.body.url,
// email: req.bodyemail,
// apply: req.body.apply,
// location: req.body.location,
// company: req.body.company,
// // path: fullPath,
// createdAt: Date.now()
// };
console.log()
request.post({url:'http://localhost:3000/api/jobs/', form: {key:'value'}}, function optionalCallback(err, response, body) {
if (err) {
return console.error('upload failed:', err);
}else{
console.log('Upload successful! Server responded with:', body);
}
return res.redirect('/jobs')
});
})
<div class="add-container">
<form name="myForm" action="/jobs" method="POST" >
<div class="form-group">
<h2>Title(Junior/Graduate/Intern)</h2>
<input type="text" name="job[title]" placeholder="e.g: Junior Front-End Developer" class="form-control" id="title" required="title">
</div>
<div class="form-group">
<h2>Company Name</h2>
<input type="text" name="company" placeholder="e.g: Microsoft" class="form-control" required="company">
</div>
<div class="form-group">
<h2>Job Description</h2>
<textarea id="mytextarea" name="description" placeholder="e.g: We are looking for a Front-End developer with about a year of experience in HTML, CSS, javaScript. Knowledge in React/Vue/Angular is a plus." class="form-control"></textarea>
</div>
<div class="form-group">
<h2>Apply by Website</h2>
<input type="text" name="url" placeholder="e.g: https://wwww.example.com/jobs" class="form-control">
</div>
<div class="form-group">
<h2>How to Apply</h2>
<input type="text" name="apply" placeholder="e.g: send your CV or Resume to..." class="form-control" required="apply">
</div>
<div class="form-group">
<h2>Company Location</h2>
<input type="text" name="location" placeholder="e.g Lagos" class="form-control" required="location">
</div>
<div class="form-group">
<label for="email">Apply by Email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="e.g: job#gmail.com" required="email">
</div>
<!-- <div class="form-group">
<label>Company logo</label>
<input type="file" name="file" single class="form-control" id="file" required="file">
</div> -->
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
remember to start app.js with body-parser urlencoded and json for json data
tested and works
//in app.js
require("dotenv").config(); //to read env variable not needed
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const dbUrl = process.env.DB_URI; //from env variable
const Model = require('./models/model.model');
mongoose
.connect(
dbUrl,
{ useNewUrlParser: true }
)
.then(() => console.log("Connected"))
.catch(error => console.log("Failed " + error));
const app = express();
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
**app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());**
htmlObject = ` <div class="add-container">
<form name="myForm" action="/job" method="POST" >
<div class="form-group">
<h2>Title(Junior/Graduate/Intern)</h2>
<input type="text" name="job[title]" placeholder="e.g: Junior Front-End Developer" class="form-control" id="title" required="title">
</div>
<div class="form-group">
<h2>Company Name</h2>
<input type="text" name="company" placeholder="e.g: Microsoft" class="form-control" required="company">
</div>
<div class="form-group">
<h2>Job Description</h2>
<textarea id="mytextarea" name="description" placeholder="e.g: We are looking for a Front-End developer with about a year of experience in HTML, CSS, javaScript. Knowledge in React/Vue/Angular is a plus." class="form-control"></textarea>
</div>
<div class="form-group">
<h2>Apply by Website</h2>
<input type="text" name="url" placeholder="e.g: https://wwww.example.com/jobs" class="form-control">
</div>
<div class="form-group">
<h2>How to Apply</h2>
<input type="text" name="apply" placeholder="e.g: send your CV or Resume to..." class="form-control" required="apply">
</div>
<div class="form-group">
<h2>Company Location</h2>
<input type="text" name="location" placeholder="e.g Lagos" class="form-control" required="location">
</div>
<div class="form-group">
<label for="email">Apply by Email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="e.g: job#gmail.com" required="email">
</div>
<!-- <div class="form-group">
<label>Company logo</label>
<input type="file" name="file" single class="form-control" id="file" required="file">
</div> -->
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
`;
app.get('/add', (req,res)=>{
res.send(htmlObject);
});
app.post('/job', (req,res)=>{
let model = new Model({
title: req.body.title,
category: req.body.category,
description: req.body.description,
type: req.body.type,
url: req.body.url,
email: req.body.email,
apply: req.body.apply,
location: req.body.location,
company: req.body.company,
path: req.body.path,
createdAt: Date.now().toString()
});
model.save().then(data=>{
res.json({message: 'success', data: data })
});
})
module.exports = app;
//in models/model.js
const mongoose = require("mongoose");
const dataSchema = mongoose.Schema({
title: { type: Number},
category: { type: Number},
description: {type: String},
type: {type: String},
url: {type: String},
email: {type: String},
apply: {type: String},
location: {type: String},
company: {type: String},
path: {type: String},
createdAt: {type: String}
});
module.exports = mongoose.model("data", dataSchema);

bootstrap form validation only one field required

I have a form that has userID and screen name input fields.
When validating I need to make sure that at least one of them is entered (if both were entered I only take one). The html:
this.addFormValidators = function () {
$('#editCreatePipeForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
ConsumerKey: {
validators: {
notEmpty: {
message: 'The Consumer Key is required'
}
}
},
ConsumerKeySecret: {
validators: {
notEmpty: {
message: 'The Consumer Key Secret is required'
}
}
},
CollectionIntervalSec: {
validators: {
notEmpty: {
message: 'The collection interval is required'
},
between: {
message: 'The collection interval must be a number greater than 10',
min: 10,
max: 1000000000
}
}
},
//KeepHistoricalDataTimeSec: {
// validators: {
// notEmpty: {
// message: 'The retain data value is required'
// },
// between: {
// message: 'The retain data value must be a number greater than 1000',
// min: 1000,
// max: 1000000000
// }
// }
//},
Description: {
validators: {
stringLength: {
max: 500,
message: 'The description must be less than 500 characters long'
}
}
}
}
}, null);
};
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="ScreenName" class="col-md-4 YcdFormLabel" title="screen name of user to retrieve">Screen name</label>
<div class="col-md-8">
<input type="text" placeholder="Screen Name" class="form-control user" autocomplete="off"
name="screenName"
id="screenName" data-bind="value: screenName, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"/>
<div class="col-md-6">
<div class="form-group">
#*<div class="col-md-8">*#
<label for="or" class="col-md-10">or</label>
#*</div>*#
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="userID" class="col-md-4 YcdFormLabel" title="user_ID of user to retrieve">User ID</label>
<div class="col-md-8">
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off"
name="userID"
id="userID" data-bind="value: userID, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>
I added another function which I called it before submitting instead of using Bootstrap and jQuery form validation.
private hasTimelineAndUsername = (): boolean => {
if (this.viewModel.searchSelection() == "timeline"
&& ((this.viewModel.userID() == "" ||
this.viewModel.userID() == null) &&
(this.viewModel.screenName() == "" ||
this.viewModel.screenName() == null))) {
return false
}
return true;
}
The submitting function:
public getCollectionParameters() {
var fv = $('#editCreatePipeForm').data('formValidation')
fv.validate();
var isValid = fv.isValid();
if (!isValid) {
toastr.error("Please fix all problems before saving");
return null;
}
if (!this.hasTimelineAndUsername()) {
toastr.clear();
toastr.error("Please type username/userID");
return null;
}
if (!this.validateData()) {
return null;
}
return JSON.stringify(ko.mapping.toJS(this.viewModel));
}
I hope my code will help you.
JSFiddle: https://jsfiddle.net/aice09/3wjdvf30/
CodePen: https://codepen.io/aice09/pen/XgQyem
GitHub: https://github.com/Ailyn09/project102/blob/master/chooseintwoinput.html
function verify() {
var screenName = document.getElementById("screenName").value;
var userID = document.getElementById("userID").value;
if (userID === '' && screenName === '') {
alert('Add value to any field');
}
if (userID !== '' && screenName === '') {
alert('Your screen name are currently empty. The value you will be taken is your screen name');
document.getElementById("takedvalue").value = userID;
}
if (userID === '' && screenName !== '') {
alert('Your user id are currently empty. The value you will be taken is your user identification');
document.getElementById("takedvalue").value = screenName;
}
if (userID !== '' && screenName !== '') {
document.getElementById("mainbtn").style.display = "none";
document.getElementById("backbtn").style.display = "initial";
document.getElementById("choosescreenName").style.display = "initial";
document.getElementById("chooseuserID").style.display = "initial";
}
}
//Reset Form
$('.backbtn').click(function () {
document.getElementById("mainbtn").style.display = "initial";
document.getElementById("backbtn").style.display = "none";
document.getElementById("choosescreenName").style.display = "none";
document.getElementById("chooseuserID").style.display = "none";
});
//Choose First Input
$('.choosescreenName').click(function () {
var screenName = document.getElementById("screenName").value;
document.getElementById("takedvalue").value = screenName;
});
//Choose Second Input
$('.chooseuserID').click(function () {
var userID = document.getElementById("userID").value;
document.getElementById("takedvalue").value = userID;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div class="container">
<form action="POST">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="screenName">Screen name</label>
<input type="text" placeholder="Screen Name" class="form-control " autocomplete="off" name="screenName" id="screenName" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="userID">User ID</label>
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off" name="userID" id="userID" />
</div>
</div>
<div class="col-md-12">
<button type="button" class="btn btn-primary" id="mainbtn" onclick="verify();">SUBMIT</button>
<button type="reset" class="btn btn-primary backbtn" id="backbtn" style="display:none;">BACK</button>
<button type="button" class="btn btn-primary choosescreenName" id="choosescreenName" style="display:none;">CHOOSE SCREEN NAME</button>
<button type="button" class="btn btn-primary chooseuserID" id="chooseuserID" style="display:none;">CHOOSE USER ID</button>
</div>
<div class="col-md-12">
<hr>
<div class="form-group">
<label for="userID">Value</label>
<input type="text" placeholder="Taken Value" class="form-control" id="takedvalue" readonly />
</div>
</div>
</div>
</form>
</div>

Categories

Resources