express-validator receives no values - javascript

I'm using express-validator in a node app. All 4 of my form fields are returning validation errors ("A name is required" and so on). When I console.log the errors variable, all values are blank:
errors: [{value: '', msg: 'A name is required.', param: 'name', location: 'body'},...
Feedback form:
<form class="feedback-form" method="POST" action="/feedback">
<div class="form-group">
<label for="feedback-form-name">Name</label>
<input
type="text"
class="form-control"
id="feedback-form-name"
name="name"
placeholder="Enter your name"
/>
</div>
<div class="form-group">
<label for="feedback-form-email">E-Mail</label>
<input
type="text"
class="form-control"
id="feedback-form-email"
name="email"
placeholder="Enter your email address"
/>
</div>
<div class="form-group">
<label for="feedback-form-title">Title</label>
<input
type="text"
class="form-control"
id="feedback-form-title"
name="title"
placeholder="Title of your feedback"
/>
</div>
<div class="form-group">
<label for="feedback-form-message">Message</label>
<textarea
type="text"
placeholder="Enter your message, then hit the submit button"
class="form-control"
name="message"
id="feedback-form-message"
rows="6"
></textarea>
</div>
<button type="submit" class="btn btn-secondary float-right">Submit</button>
</form>
And my router:
router.post(
"/",
[
check("name").trim().isLength({ min: 3 }).escape().withMessage("A name is required."),
check("email").trim().isEmail().normalizeEmail().withMessage("A valid e-mail is required."),
check("title").trim().isLength({ min: 3 }).withMessage("A valid title is required."),
check("message").trim().isLength({ min: 3 }).withMessage("A valid message is required."),
],
(request, response) => {
const errors = validationResult(request);
console.log(errors);
if (!errors.isEmpty()) {
request.session.feedback = {
errors: errors.array(),
};
return response.redirect("/feedback");
}
return response.send("Feedback form posted");
}
);
return router;
Why aren't the form values passing to the router's post method?

You need to access form fields in request.body followed by their respective name as described in THIS post.

Related

how to connect input tags with form fields in django

I have input tags in an HTML page and I want to connect those with form fields
I have linked forms with a model to save the details in the database. when I am adding signup-form as a parameter in return, the model is displaying its own form and my own form is also displaying. I want the code to connect my Html form with the Django form using the name attribute
login.html
<form method = "POST" enctype="multipart/form-data" id="register" class="input-group-register needs-validation" novalidate oninput='up2.setCustomValidity(up2.value != up.value ? "Passwords do not match." : "")'>
<!-- {{ signup_form.as_p }} -->
{% csrf_token %}
<input type="text" class="input-field" id="firstname" placeholder="First Name" name = "first_name" required>
<div class="invalid-feedback">Please enter a valid first name.</div>
<input type="text" class="input-field" id="lastname" name = "last_name" placeholder="Last Name" required>
<div class="invalid-feedback">Please enter a valid last name.</div>
<input type="email" class="input-field" id="email" name = "emailid" placeholder="Email" required>
<div class="invalid-feedback">Please enter a valid Email Address.</div>
<input type="number" class="input-field" id="mobile" name = "number" placeholder="Mobile" required>
<div class="invalid-feedback">Please enter your Mobile Number.</div>
<input type="password" class="input-field" id="password" placeholder="Enter Password" name="up" required>
<div class="invalid-feedback">Please enter your password.</div>
<input type="password" class="input-field" id="confirmpassword" placeholder="Confirm Password" name="up2" required>
<div class="invalid-feedback">Password doesn't match.</div>
<input type="checkbox" class="check-box" required> <span> I agree to the Terms & Conditions </span>
<div class="invalid-feedback">You must agree before submitting.</div>
<button type="submit" name = "submit" class="submit-btn" value="checkform1"> SignUp </button>
</form>
views.py
def user_login(request):
if request.method=='POST':
register_status = False
if request.POST.get('submit') == 'checkform1':
return render(request,'first_app/Login.html')
forms.py
class SignupForm(forms.ModelForm):
class Meta:
model = FormSl
fields = '__all__'
widgets = {
'up' : forms.PasswordInput(),
'up2' : forms.PasswordInput()
}
models.py
class FormSl(models.Model):
# for signup and login
first_name = models.CharField(max_length= 32, unique = True)
last_name = models.CharField(max_length= 32, unique = True)
emailid = models.EmailField()
number = models.IntegerField()
up = models.CharField(max_length = 32, unique = True)
up2 = models.CharField(max_length = 32, unique = True)
def __str__(self):
return self.first_name
You can use jquery for that. Jquery has prepend() method for that. You can move this fields to input's container p element and show in there. Also you can use help_text field option in django for your forms.

Create JSON object from vuejs form data

I'm trying to create a JSON object from form data on submit.
I've managed to get it working with a variable. Is there a better way to create a JSON object?
Form
<form #submit.prevent="submit">
<div class="form-group">
<label class="inputa-label" for="exampleInputEmail1"
>Email address</label
>
<input
type="email"
class="form-control inputa"
id="exampleInputEmail1"
placeholder="Enter email"
required
v-model="email"
/>
</div>
<div class="form-group">
<label class="inputa-label" for="exampleInputPassword1"
>Phone number</label
>
<input
type="number"
class="form-control inputa"
id="exampleInputPassword1"
placeholder="Phone"
v-model="phone"
/>
</div>
<div class="form-group">
<label class="inputa-label" for="exampleInputPassword1"
>Information</label
>
<textarea
class="form-control inputa"
aria-label="With textarea"
v-model="information"
></textarea>
</div>
<button
type="submit"
style="font-weight:600; padding: .8125rem 1.25rem"
class="btn btn-primary"
>
Submit
</button>
</form>
Method:
data() {
return {
email:"",
phone:"",
information:"",
};
},
methods: {
submit() {
var data = '{ "Email":"' + this.email + '" , "Phone":"' + this.phone + '", "Information":"' + this.information + '" }';
},
},
I've got it working with a variable, but I want to know if there is a better way to do this.
Answering the question, I think what you're looking for is JSON.stringify():
const data = JSON.stringify({
Email: this.email,
Phone: this.phone,
Information: this.information
})

jQuery form validate and submit multiple forms on the the same page gives "Uncaught SyntaxError: Invalid or unexpected token"

I am trying to submit user details to a MailChimp list via PHP for multiple forms on the same page.
My code is as follows:
index.html
<form id="contact-form" name="contact-form" action="assets/php/send.php" method="post" novalidate="novalidate">
<fieldset>
<div id="alert-area"></div>
<input class="col-sm-6 col-xs-12" id="fname" type="text" name="fname" placeholder="first name">
<input class="col-sm-6 col-xs-12" id="lname" type="text" name="lname" placeholder="last name">
<input class="col-sm-6 col-xs-12" id="number" type="text" name="number" placeholder="number">
<input class="col-sm-6 col-xs-12" id="email" type="text" name="email" placeholder="email">
<input class="btn btn-default blue" id="submit" type="submit" name="submit" value="Submit" onclick="ga('send', 'event', ‘scholars’, 'click', ‘s-rs’);">
<div id='response'></div>
</fieldset>
</form>
<form id="contact-form" name="contact-form" action="assets/php/send.php" method="post" novalidate="novalidate">
<fieldset>
<div id="alert-area"></div>
<input class="col-sm-6 col-xs-12" id="fname" type="text" name="fname" placeholder="first name">
<input class="col-sm-6 col-xs-12" id="lname" type="text" name="lname" placeholder="last name">
<input class="col-sm-6 col-xs-12" id="number" type="text" name="number" placeholder="number">
<input class="col-sm-6 col-xs-12" id="email" type="text" name="email" placeholder="email">
<input class="btn btn-default blue" id="submit" type="submit" name="submit" value="Submit" onclick="ga('send', 'event', ‘scholars’, 'click', ‘s-rs’);">
<div id='response'></div>
</fieldset>
</form>
send.php
<?php
$api_key = 'XXXXXXXXX';
$list_id = 'XXXXXXXXXX';
// Include the MailChimp API wrapper
include('./inc/MailChimp.php');
// Then call/use the class
use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp($api_key);
// Submit subscriber data to MailChimp
$result = $MailChimp->post("lists/$list_id/members", [
'email_address' => $_POST["email"],
'merge_fields' => ['FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"], 'NUMBER'=>$_POST["number"]],
'status' => 'subscribed',
]);
if ($MailChimp->success()) {
// Success message
echo "<h4>Thank you for your interest. </h4>";
} else {
// Display error
echo "<h4>Whoops! Please try again.</h4>";
}
?>
Validate function
function validateForm(){
$('form').each(function(){
$(this).validate({
// all fields are required
rules: {
fname: {
required: true
},
lname: {
required: true
},
email: {
required: true,
email: true
},
number: {
required: true,
number: true
}
},
// if valid, post data via AJAX
submitHandler: function(form){
$.post("assets/php/send.php", {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
number: $("#number").val()
}, function (data) {
$('#response').html(data);
});
}
})
})
}
This works fine for the first form but gives a "Uncaught SyntaxError: Invalid or unexpected token" for other forms
The SyntaxError was because of rogue quote marks in the ga onCLick event.
Solved the multiple form submit issue with the following jQuery code
function validateForm(){
$('form').each(function(){
$(this).validate({
// all fields are required
rules: {
fname: {
required: true
},
lname: {
required: true
},
email: {
required: true,
email: true
},
number: {
required: true,
number: true
}
},
// if valid, post data via AJAX
submitHandler: function (form) {
$.post("assets/php/send.php", $(form).serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {})
, function (data) {
$(form).find('#response').html(data);
});
}
})
})
}
All forms have unique ID. This code works with modal form too. Hope this helps!

Meteor.call method not found

I am working my way through the Microscope project in Discover Meteor and I have hit a problem. I am getting a 'Method not found' error for the following code:
HTML Template - microscope/client/templates/posts/post_submit.html
<template name="postSubmit">
<form class="main form">
<div class="form-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input name="url" id="url" type="text" value="" placeholder="Your URL" class="form-control"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control"/>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
JS - microscope/client/templates/posts/post_submit.js
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
}
});
I am not sure how to debug this as I am getting no errors in the console. Please can anyone suggest where I am going wrong?
Very likely that you need to add the method postInsert to the server side. If you're following along in Discover Meteor, they do that in the next section - https://book.discovermeteor.com/chapter/creating-posts
For example, you put the method in a file called lib/collections/posts.js like this
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});

Why is one of my jQuery Validation rules being randomly applied to another field?

I am having a strange issue with the jQuery Validation plugin.
I have a field TwitterUsername that is not required and has no validation. If I don't enter anything into this field it works fine. However, if I enter any value in this field I am presented with the Please enter a valid email address. message that is tied to the EmailAddress field above it.
You can see this behavior at: http://eat-sleep-code.com/#!/contact
Below is the main code of this webpage:
<form role="form" id="ContactMessageForm">
<div class="form-group">
<label for="FirstName" class="sr-only">First Name</label>
<input type="text" id="FirstName" name="FirstName" maxlength="255" class="form-control" placeholder="First Name" />
</div>
<div class="form-group">
<label for="LastName" class="sr-only">Last Name</label>
<input type="text" id="LastName" name="LastName" maxlength="255" class="form-control" placeholder="Last Name" />
</div>
<div class="form-group">
<label for="EmailAddress" class="sr-only">Email Address</label>
<input type="email" id="EmailAddress" name="EmailAddress" maxlength="255" class="form-control" placeholder="Email Address" />
</div>
<div class="form-group">
<label for="TwitterUsername" class="sr-only">Twitter Username</label>
<input type="text" id="TwitterUsername" name="TwitterUsername" maxlength="255" class="form-control" placeholder="Twitter Username" />
</div>
<div class="form-group">
<label for="Subject" class="sr-only">Subject</label>
<input type="text" id="Subject" name="Subject" maxlength="255" class="form-control" placeholder="Subject" />
</div>
<div class="form-group">
<label for="Message" class="sr-only">Message</label>
<textarea id="Message" name="Message" rows="5" class="form-control" placeholder="Message"></textarea>
</div>
<button type="button" class="btn btn-default" id="ContactMessageSendButton">Send</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#ContactMessageSentAlert').hide();
$('#ContactMessageForm').show();
$.validator.addMethod('twitterUsername', function(value, element) {
return this.optional(element) || /^(#?[a-zA-Z0-9]{1,15})$/.test(value);
}, '');
var validator = $('#ContactMessageForm').validate({
errorClass: 'has-error',
errorElement: 'div',
rules: {
FirstName: {required: true},
LastName: {required: true},
EmailAddress: {required: true, email: true},
TwitterUsername: {twitterUsername: true},
Subject: {required: true},
Message: {required: true}
},
messages: {
FirstName: {required: 'Please enter your first name.'},
LastName: {required: 'Please enter your last name.'},
EmailAddress: {required: 'Please enter your email address.', email: 'Please enter a valid email address.'},
TwitterUsername: {twitterUsername: 'Please enter a valid Twitter username.'},
Subject: {required: 'Please enter a subject.'},
Message: {required: 'Please enter a message.'}
},
errorPlacement: function (error, element) {
$(error).insertBefore($(element));
},
highlight: function(element, errorClass) {
$(element).parent('div').addClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent('div').removeClass(errorClass);
},
onfocusout: false
});
});
</script>
<script type="text/javascript">
/* Assign an OnClick function to items in the "Send" button */
$('#ContactMessageSendButton').click(function(e) {
$(document).ready(function () {
var form = $('#ContactMessageForm');
form.validate();
if (form.valid() === true) {
var sender = $.trim($('#EmailAddress').val());
var senderName = $.trim($('#FirstName').val()) + ' ' + $.trim($('#LastName').val());
var recipient = 'info#eat-sleep-code.com';
var subject = $.trim($('#Subject').val());
var message = $.trim($('#Message').val()) + '<br />' + $.trim($('#TwitterUsername').val());
sendMail(sender, senderName, recipient, subject, message);
}
});
});
</script>

Categories

Resources