validate the form and then post? - asp.net

i have a form with few fileds and a submit button... when i click on the submit button the form should validate and throw me an error of missing data but whats happening is that, it post the data and than validate the form
what should i do to validate the form and then post the form?
<body>
<form class="cmxform" id="commentForm" method="post" action="">
<div class="subColumns paragraph">
<div class="lefty">
<div class="fontWeight7">
<label for="first_name">
First Name:</label>
<input id="first_name" class="text required" maxlength="200"
name="first_name" />
</div>
</div>
<div class="cdc-left">
<div class="fontWeight7">
<label for="last_initial">
Last Initial:</label>
<input id="last_initial" class="required text" maxlength="200"
name="last_initial" />
</div>
</div>
</div>
<input id="btnRegister" name="btnRegister" class="submit" type="submit" value="Submit Your Answer" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#commentForm").validate();
// validate the comment form when it is submitted
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
$("#commentForm").validate({
submitHandler: PostData
});
});
function PostData() {
debugger
var _firstName = commentForm.first_name.value;// $('#first_name').value; //first_name.value;
var _lastName = $('#last_initial').value; //last_initial.value;
var _city = $('#city').value; //city.value;
var _state = $('#state').value; //state.value;
var _country = $('#country').value; //country.value;
}
</script>

You're hooking up the the click event on the button, which happens before the submit event on the form, instead use the submitHandler callback option for .validate(), like this:
$("#commentForm").validate({
submitHandler: PostData
});
...and remove this click handler completely:
$('#btnRegister').click(function () {
PostData();
});
The submitHandler only executes when the validation was successful, which would be what you want here.

Why not do server-side validation using ASP.NET's validation controls? It has the advantage of being harder to override, as client-side validation can be disabled if the user configures his browser to not run JavaScript.

Related

Meteor.js loginWithGoogle does nothing

I am working on my first Meteor app that uses OAuth for login. Prior to this, all of my projects have used only the accounts-password portions.
I have a simple login for with a button to login via Google:
<template name="login">
<form id="login" role="form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" class="form-control" placeholder="Username" />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" />
</div>
<button id="signin" class="btn btn-primary">Sign in</button>
<hr />
Or:<br />
<button id="loginWithFacebook">Login with Facebook</button>
<button id="loginWithGoogle">Login with Google</button>
<button id="loginWithTwitter">Login with Twitter</button>
</form>
</template>
I then have a event handler to capture the button click and call the loginWithGoogle:
...
"click #loginWithGoogle": function(e, t){
Meteor.loginWithGoogle({
requestPermissions: [],
loginStyle: "popup"
}, function(err) {
if (err) {
// TODO Need to do something here with the error...
console.log('Error: ', err);
} else {
Router.go('home');
}
});
}
...
On the server I setup OAuth for Google like thus:
ServiceConfiguration.configurations.remove({
service: "google"
});
ServiceConfiguration.configurations.insert({
service: "google",
clientId: "000000000000000",
loginStyle: "popup",
secret: "000000000"
});
Accounts.onCreateUser(function (options, user) {
console.log('Creating user: ' + user.username);
return user;
});
And in my route I have this:
if (Meteor.isClient) {
// Initialize the loading template before hand
Router.onBeforeAction('loading');
// Map the routes
Router.map(function() {
// Homepage
this.route('home', {
path: '/',
onBeforeAction: function() {
if (!Meteor.user()) {
console.log('User is not logged in. Displaying login form.');
Router.go('login');
} else {
console.log('User is already logged in:', Meteor.user());
}
}
});
// Login page
this.route('login', {
path: '/login'
});
});
}
So, I get the console log in the browser saying User is not logged in. Displaying login form., and when I click the Login with Google button I get the popup asking which Google account I want to use, then the confirmation page. But when I click the Accept button I get nothing. The Accounts.onCreateUser() doesn't seem to run, nor does the callback code on the loginWithGoogle(). How do I get this configured correctly so that the callback runs, and ultimately I am re-directed back to my homepage?
Your onCreateUser doesn't work because you don't have username specified.
Try using
if(user.services.google)
user.username = user.services.google.name
And by the way, why won't you use {{>loginButtons}}?

Meteor and filepicker-plus package

I am having a little bit of trouble outputting a image after a filepicker selection with the file picker plus package from meteor. How to I grab the uploaded image url or file path, so I can pass it into a form input and put it in a collection. Putting in into the collection isnt the part I am worried about its getting the path that I am having trouble with cheers.
All contained in postSubmit template.
I have a form with
<input type="filepicker" name="myName" />
and a img output in the same template
<img src="{{filepickerIdToUrl myName}}">
and a router file containg
Router.onBeforeAction(function(){
loadFilePicker('magickey');
//can leave out key if its in settings
this.next();
},{only:['postSubmit']});
Here is the full postSubmit template
<template name="postSubmit">
<form>
<label for="title">Title</label>
<input name="title" id="title" type="text" value="" placeholder="Name your post"/>
<button id="uploadImage" class="btn btn-info btn-sm"><i class="fa fa-upload"></i> Upload</button>
<input type="submit" value="Submit"/>
</form>
<img id="imagePreview" class="img-responsive" src="{{filepickerIdToImageUrl imageId placehold_it='500x350' h=200 w=300}}"/>
<button id="removeImage" class="btn btn-warning btn-sm"><i class="fa fa-trash-o"></i> Remove</button>
This is also my postSubmit events
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
title: $(e.target).find('[name=title]').val(),
image: $(e.target).find('[name=image]').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});
});
}
});
Thanks to Nate and the google groups link above, I got it working.
Here is my solved code, Right now it only shows the preview on the form and you can remove it by clearing the session value, but it will be easy enough to grab that session value and put it into the form on submit.
Thanks again Nate.
Template.postSubmit.created = function(){
Session.setDefault("imageId", null);
Session.setDefault("imageKey", null);
};
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
title: $(e.target).find('[name=title]').val(),
image: $(e.target).find('[name=image]').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});
});
},
'click #uploadImage':function(event, template){
event.preventDefault();
filepicker.pickAndStore(
{
mimetypes: ['image/gif','image/jpeg','image/png'],
multiple: false
},{
access:"public"
},
function(InkBlobs){
// the upload is now complete to filepicker - but the form hasnt persisted the values to our collection yet
Session.set("imageId", _.last(_.first(InkBlobs).url.split("/")));
Session.set("imageKey", _.first(InkBlobs).key);
// once the session changes are made, the form will now have the new values, including a preview of the image uploaded
},
function(FPError){
log.error(FPError.toString());
}
);
},
'click #removeImage':function(event, template){
event.preventDefault();
Session.set("imageId", "remove");
Session.set("imageKey", "remove");
}
});
Template.postSubmit.helpers({
'hideRemove':function(){
return Session.equals("imageId", null) || Session.equals("imageId", "remove");
},
'imageId':function(){
if(Session.equals("imageId", "remove"))
return "";
else
return Session.get("imageId") || "";
},
'imageKey':function(){
if(Session.equals("imageKey", "remove"))
return "";
else
return Session.get("imageKey") || "";
}
});

How do I notify the client of success/failure when creating users with no password?

I'm building an application that doesn't support public registration. New users will be created by an existing user and an enrollment email will be sent to the new user's email address. I've got this all working, but my implementation feels hackish.
Here's the code, so far.
Template:
<template name="addUser">
<form role="form">
<div class="form-group">
<label for="firstName">First Name</label>
<input name="firstName" class="form-control" placeholder="First Name" />
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input name="lastName" class="form-control" placeholder="Last Name" />
</div>
<div class="form-group">
<label for="email">Email</label>
<input name="email" class="form-control" placeholder="Email" />
</div>
<button type="submit" class="btn btn-primary">{{faIcon 'plus'}} Add User</button>
</form>
</template>
Template's Javascript:
Template.addUser.events({
'submit form': function (e, t) {
e.preventDefault();
var attrs = {
email: t.find('[name="email"]').value,
profile: {
firstName: t.find('[name="firstName"]').value,
lastName: t.find('[name="lastName"]').value,
}
};
Meteor.call('addUser', attrs, function (err) {
if (err) {
Errors.throw(err.reason);
} else {
Router.go('home');
}
});
}
});
My addUser method
Meteor.methods({
addUser: function (attrs) {
var user = Meteor.user();
if (!user) throw new Meteor.Error(401, 'Please login.');
if (!attrs.profile.firstName) throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.profile.lastName) throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.email) throw new Meteor.Error(422, 'Please include an email.');
var user = _.pick(attrs, ['firstName', 'lastName', 'email']);
if (Meteor.isServer) {
var newUserId = Accounts.createUser(attrs);
Accounts.sendEnrollmentEmail(newUserId);
}
}
});
Since Accounts.createUser requires a password on the client side, I can't figure out how to notify the client of success or failure short of doing something hacky with Session. What's a good way to go about doing such a thing?
First, put addUser method on server only (i.e. in server dir):
Meteor.methods({
addUser: function (attrs) {
var user = Meteor.user();
if (!user) // you can also check this.userId here
throw new Meteor.Error(401, 'Please login.');
if (!attrs.profile.firstName)
throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.profile.lastName)
throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.email)
throw new Meteor.Error(422, 'Please include an email.');
var user = _.pick(attrs, ['firstName', 'lastName', 'email']);
var newUserId = Accounts.createUser(attrs);
Accounts.sendEnrollmentEmail(newUserId);
}
});
Then, on the client, you can do something like:
Meteor.call('addUser', attrs, function (err) {
if (err) {
console.log('something went wrong :(');
}
});
Give the user a default password.
(I recommend using the check() function inside your addUser method – replacing some of your if statements. Also, you don't need Meteor.isServer as long as you put the js-file inside the /server folder.)

How to change the default color of validation message in knockoutJS

I have applied validation on HTML page through knockoutJS..when i suppose to click the submit button the validation works well but the message is displaying with black color...I want it to show with Red..Here is a small piece of my View page:
<tr>
<td align="right" style="width: 30%;">
<b>Name :</b>
</td>
<td align="left" style="width: 70%;">
<input data-bind="value: EmployeeName" placeholder="Employee Name" class="txt"
type="text" />
</td>
</tr>
And My View Model (continued from the above):
var EmpViewModel = function () {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.EmployeeCode = ko.observable("").extend({ required: { message: 'Please enter your Employee Code.'} }); //WANT TO CHANGE THIS MESSAGE TEXT COLOR TO RED..
self.EmployeeName = ko.observable("").extend({ required: { message: 'Please enter your Name.'} });
self.Dob = ko.observable("").extend({ required: { message: 'Please enter your Date of Birth.'} });
self.Age = ko.observable("").extend({ number: true, required: { message: 'Please enter your Age.'} });
self.ContactNumber = ko.observable("").extend({ number: true, required: { message: 'Please enter your Contact Number.'} });
self.EmailID = ko.observable("").extend({ email: true, required: { message: 'Please enter your EmailID.'} });
self.Address = ko.observable("").extend({ required: { message: 'Please enter your Address.'} });
self.MaritalStatus = ko.observable("");
self.City = ko.observable("");
self.Is_Reference = ko.observable("");
//The Object which stored data entered in the observables
var EmpData = {
EmpCode: self.EmployeeCode,
EmpName: self.EmployeeName,
Dob: self.Dob,
Age: self.Age,
ContactNumber: self.ContactNumber,
MaritalStatus: self.MaritalStatus,
EmailID: self.EmailID,
Address: self.Address,
City: self.City,
Is_Reference: self.Is_Reference
};
self.errors = ko.validation.group(this, { deep: true, observable: false });
//Declare an ObservableArray for Storing the JSON Response
self.Employees = ko.observableArray([]);
//Function to perform POST (insert Employee) operation
self.save = function () {
// check if valid
if (self.errors().length > 0) {
self.errors.showAllMessages();
return;
}
//Ajax call to Insert the Employee
$.ajax({
type: "POST",
url: "/Exercise/Save/",
data: ko.toJSON(this), //Convert the Observable Data into JSON
contentType: "application/json",
success: function (data) {
alert(data);
window.close();
opener.location.reload(true);
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
}
ko.applyBindings(new EmpViewModel());
You can create a custom message template.
<script type="text/html" id="myCustomTemplate">
<span
class="yourCustomCssClass"
data-bind="if: field.isModified() && !field.isValid(),
text: field.error"></span>
</script>
And configure knockout-validation to use it:
ko.validation.init({ messageTemplate: 'myCustomTemplate' });
Or like described here: https://github.com/ericmbarnard/Knockout-Validation/wiki/Configuration

Knockout js form submit to spring controller

How to pass form parameters into spring controller.
I need to submit the below form into this url "submit.htm".
<form data-bind="submit: save" action="forms/submit.htm" method="post">
<fieldset>
<legend>User: <span data-bind='text: errors().length'></span> errors</legend>
<label>First name: <input data-bind='value: firstName'/></label>
<label>Last name: <input data-bind='value: lastName'/></label>
</fieldset>
<button type="submit">Go</button>
</form>
JS:
var viewModel = {
firstName: ko.observable().extend({
required: true,
minLength: 2,
maxLength: 10
}),
lastName: ko.observable().extend({
required: true
}),
tasks: ko.observableArray([]),
save: function() {
if (viewModel.errors().length == 0) {
ko.utils.postJson($("form")[0], this);
} else {
alert('Please check your submission.');
viewModel.errors.showAllMessages();
}
}
};
viewModel.errors = ko.validation.group(viewModel);
ko.applyBindings(viewModel);
this is going to my controller.
But I didnot get those parameters in my controller. Also I dont know the way to get these params in my controller.

Resources