Unobtrusive validation with Jquery Steps Wizard - asp.net-mvc-5

Recently I asked a question for how to customize the JQuery Steps as I wanted to use partial views instead of static content. I have partially solved that problem by using the following code supported by jquery-steps,
<h3>Step 1</h3>
<section data-mode="async" data-url="/Formation/RenderStep1"></section>
<h3>Step 2</h3>
<section data-mode="async" data-url="/Formation/RenderStep2"></section>
Now the big problem I am facing right now is how to use unobtrusive validation. I don't want to use JQuery custom validation and there must be some way of using Obtrusive with it.
Each partial view that is rendered has its own form. I want to validate the form in the onStepChanging function of jquery-steps,
$("#my-steps").steps({
headerTag: "h3",
bodyTag: "section",
contentMode: "async",
transitionEffect: "fade",
stepsOrientation: "vertical",
onStepChanging: function (event, currentIndex, newIndex) {
return true;
}
});
I have tried calling $.validator.unobtrusvie.parse('#myform'); in the onStepChanging function but ('#myform') is undefined and still I don't know that whether this is the right way to call the unobtrusive validation manually. Kindly guide me and show me the direction to achieve this. Any help will be highly appreciated.

It sounds like your trying manage multiple forms within the JQuery Steps library and I don't think that is what its intended for.
When you configure JQuery Steps, you set it up against the form in your view.
Unobtrusive JQuery Validation is looking at the model in your view and automatically configuring the HTML with the relevant data attributes for error handling.
This validation should be firing at the client side automatically.
There shouldn't be a problem with using Partial View's, as long as there encapsulated within the same form element.
What is the requirement to have each partial view wrapped in its own form? If your trying to make multiple posts throughout the JQuery Steps form wizard, your defeating the object.
At each step in the JQuery Steps form, your only validating the one form like this :-
onStepChanging: function (event, currentIndex, newIndex) {
//Allways allow user to move backwards.
if (currentIndex > newIndex) {
return true;
}
// Remove the validation errors from the next step, incase user has previously visited it.
var form = $(this);
if (currentIndex < newIndex) {
// remove error styles
$(".body:eq(" + newIndex + ") label.error", form).remove();
$(".body:eq(" + newIndex + ") .error", form).removeClass("error");
}
//disable validation on fields that are disabled or hidden.
form.validate().settings.ignore = ":disabled,:hidden";
return form.valid();
}
Once the user has finished entering data, and the client side validation has been met, you hook into the onFinished method and post the form :-
onFinished: function (event, currentIndex) {
var form = $(this);
form.submit();
}
The purpose of JQuery Steps is to allow the user to have a fluid experience of filling out a form and to not be overwhelmed with the number of questions been asked.
From the developers perspective, it enables us to split up the form into nice size-able chunks without having to worry about saving progress between screens or losing the state of the form data and allows us to capture all of the required data with only having to make that one post once all validation criteria has been met.

I tried the formvalidation plugin, it will relax your mind from searching in validation without form tag or validation without submit the form that's the issue I solved when I tried it.
I know it's not free but you can try it from here, personally I like it
First update height after validation
<style type="text/css">
/* Adjust the height of section */
#profileForm .content {
min-height: 100px;
}
#profileForm .content > .body {
width: 100%;
height: auto;
padding: 15px;
position: relative;
}
Second, add data-steps index to your section*
<form id="profileForm" method="post" class="form-horizontal">
<h2>Account</h2>
<section data-step="0">
<div class="form-group">
<label class="col-xs-3 control-label">Username</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Email</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="email" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Retype password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="confirmPassword" />
</div>
</div>
</section>
Third, javascript code
<script>
## // to adjust step height to fit frame after showing validation messages##
$(document).ready(function() {
function adjustIframeHeight() {
var $body = $('body'),
$iframe = $body.data('iframe.fv');
if ($iframe) {
// Adjust the height of iframe
$iframe.height($body.height());
}
}
// IMPORTANT: You must call .steps() before calling .formValidation()
$('#profileForm')
// setps setup
.steps({
headerTag: 'h2',
bodyTag: 'section',
onStepChanged: function(e, currentIndex, priorIndex) {
// You don't need to care about it
// It is for the specific demo
adjustIframeHeight();
},
// Triggered when clicking the Previous/Next buttons
// to apply validation to your section
onStepChanging: function(e, currentIndex, newIndex) {
var fv = $('#profileForm').data('formValidation'), // FormValidation instance
// The current step container
$container = $('#profileForm').find('section[data-step="' + currentIndex +'"]');
// Validate the container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
// Do not jump to the next step
return false;
}
return true;
},
// Triggered when clicking the Finish button
onFinishing: function(e, currentIndex) {
var fv = $('#profileForm').data('formValidation'),
$container = $('#profileForm').find('section[data-step="' + currentIndex +'"]');
// Validate the last step container
fv.validateContainer($container);
var isValidStep = fv.isValidContainer($container);
if (isValidStep === false || isValidStep === null) {
return false;
}
return true;
},
onFinished: function(e, currentIndex) {
// Uncomment the following line to submit the form using the defaultSubmit() method
// $('#profileForm').formValidation('defaultSubmit');
// For testing purpose
$('#welcomeModal').modal();
}
})
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
// This option will not ignore invisible fields which belong to inactive panels
excluded: ':disabled',
fields: {
username: {
validators: {
notEmpty: {
// for asp.net i used element attribute to integerated with unobtrusive validation
// message :$('username').attr('data-val-required')
message: 'The username is required'
},
stringLength: {
min: 6,
max: 30,
message: 'The username must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.]+$/,
message: 'The username can only consist of alphabetical, number, dot and underscore'
}
}
},
email: {
validators: {
notEmpty: {
message: 'The email address is required'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required'
},
different: {
field: 'username',
message: 'The password cannot be the same as username'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The confirm password is required'
},
identical: {
field: 'password',
message: 'The confirm password must be the same as original one'
}
}
}
}
});

Related

Can't Edit and Update properties with form Reactjs and MongoDB

So I'm using Nodejs, MongoDB and Reactjs
and I'm trying to Edit properties of projects.
I have multiple projects and when I want to edit properties of one I can't do it. We can access to properties inside inputs, we can see Title and Type but can't even delete, write, he access to properties by its ID but then I can't change it, I guess I have multiple problems here than.
I'll write here my server code, and my Edit/Update project page and a gif with an example when I say that I can't even change anything on inputs.
My server code:
//Render Edit Project Page byId
app.get('/dashboard/project/:id/edit', function(req, res){
let id = req.params.id;
Project.findById(id).exec((err, project) => {
if (err) {
console.log(err);
}
res.json(project);
});
}
//Update Projects Properties byId
app.put('/dashboard/project/:id/edit', function(req, res){
var id = req.params.id;
var project = {
title: req.body.title,
typeOfProduction: req.body.typeOfProduction
};
Project.findByIdAndUpdate(id, project, {new: true},
function(err){
if(err){
console.log(err);
}
res.json(project);
})
};
My React Component Edit Project Page
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import './EditProject.css';
class EditProject extends Component {
constructor(props){
super(props);
this.state = {
//project: {}
title: '',
typeOfProduction: ''
};
}
inputChangedHandler = (event) => {
const updatedProject = event.target.value;
}
componentDidMount() {
// console.log("PROPS " + JSON.stringify(this.props));
const { match: { params } } = this.props;
fetch(`/dashboard/project/${params.id}/edit`)
.then(response => { return response.json()
}).then(project => {
console.log(JSON.stringify(project));
this.setState({
//project: project
title: project.title,
typeOfProduction: project.typeOfProduction
})
})
}
render() {
return (
<div className="EditProject"> EDIT
<form method="POST" action="/dashboard/project/${params.id}/edit?_method=PUT">
<div className="form-group container">
<label className="form--title">Title</label>
<input type="text" className="form-control " value={this.state.title} name="title" ref="title" onChange={(event)=>this.inputChangedHandler(event)}/>
</div>
<div className="form-group container">
<label className="form--title">Type of Production</label>
<input type="text" className="form-control " value={this.state.typeOfProduction} name="typeOfProduction" ref="typeOfProduction" onChange={(event)=>this.inputChangedHandler(event)}/>
</div>
<div className="form-group container button">
<button type="submit" className="btn btn-default" value="Submit" onClcik={() => onsubmit(form)}>Update</button>
</div>
</form>
</div>
);
}
}
export default EditProject;
Erros that I have:
1- DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
2- Inputs can't change
3- When click "Update" button:
I think your update override the entire object because you forgot the $set operator. This is the operator to change only the atributtes of an object and not the entire object replacing!
Example:
Model.update(query, { $set: { name: 'jason bourne' }}, options, callback)
First of all, concerning the deprecation warning, you need to change the method findAndModify (As I do not see it here, I guess you're using it elsewhere, or maybe one of the methods you use is calling it) by one of the suggested methods and change your code accordingly.
Then, you need to learn about React and controlled components : https://reactjs.org/docs/forms.html
You need to set the component's state in your onChange handler, such as :
this.setState({
title: event.target.value // or typeOfProduction, depending on wich element fired the event
});
This is called a controlled component in React.
Concerning the response body you get when clicking on Update button, this is actually what you asked for :
res.json(project);
returns the project variable as a JSON file, which is displayed on your screenshot.
See this question for more information about it : Proper way to return JSON using node or Express
Try replace "value" in input tag with "placeholder"

Knockout two way binding not working with Sharepoint modal dialog

I'm trying two way binding (knockout observables) with sharepoint modal dialog
var ViewModel = function () {
var self = this;
self.firstName = "Irfanullah";
self.lastName = ko.observable('M.');
self.fullName = ko.computed(function () {
return self.firstName + ' ' + self.lastName();
});
};
ko.applyBindings(new ViewModel());
<button type=button onclick="openDialog2()">click me</button>
<div id="wrap" style="display:none">
<div id="d10" class="dialogHolder">
<div id="kobasic">
<h4>Editable data</h4>
<p><input type="text" data-bind="value: firstName" /></p>
<p><input type="text" data-bind="value: lastName" /></p>
<p>Full Name: <span data-bind="text: fullName"></span></p>
</div>
</div>
When i test this code on sharepoint wiki page its working good, but when i use same code on sharepoint dialog it shows values (one way binding)but two way binding/ko.observable() does not work (when i type something in lastname text box it does not update fullname)
function openDialog2() {
var e = document.getElementById('d10');
var options = {
title: "Test Knockout",
width: 700,
height: 800,
html: e.cloneNode(true)
};
mydialog = SP.UI.ModalDialog.showModalDialog(options);
}
I believe that is alll becase e.cloneNode(true) but i could not figureout alternat solution
For SharePoint dialogs I am using this approach:
(note: jQuery needed)
// create dom element
var element = document.createElement('div');
// apply my custom view
$(element).append('<!--my HTML -->');
// apply knockout bindings
ko.applyBindings(myViewModel, element);
// show sharepoint modal dialog
var options = {
allowMaximize: false,
html: element,
title: "My title",
autoSize: true,
showClose: true,
dialogReturnValueCallback: myCallback
};
SP.UI.ModalDialog.showModalDialog(options);
So in your case:
var element = document.createElement('div');
$(element).append('<div id="d10" class="dialogHolder"><div id="kobasic"><h4>Editable data</h4><p><input type="text" data-bind="value: firstName" /></p><p><input type="text" data-bind="value: lastName" /></p><p>Full Name: <span data-bind="text: fullName"></span></p></div></div>');
ko.applyBindings(new ViewModel(), element);
var options = {
allowMaximize: false,
html: element,
title: "My title",
autoSize: true,
showClose: true,
dialogReturnValueCallback: myCallback
};
SP.UI.ModalDialog.showModalDialog(options);

How to add card holder's name to Stripe checkout using Elements?

I need to add an additional field to my custom form, I want to add the name of the credit card.
I tried in the following way:
var cardNameElement = elements.create('cardName', {
style: style
//, placeholder: 'Custom card number placeholder',
});
cardNameElement.mount('#card-name-element');
<div id="card-name-element" class="field"></div>
But this does not work, in its documentation only allows to perform these procedures validating only four elements or data: cardNumber, cardExpiry, cardCvc, postalCode.
How can I add the name of the credit card and validate it using stripe.js
My code:
var stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
var elements = stripe.elements();
var style = {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: 'Helvetica Neue',
fontSize: '15px',
'::placeholder': {
color: '#CFD7E0',
},
},
};
var cardNumberElement = elements.create('cardNumber', {
style: style
//, placeholder: 'Custom card number placeholder',
});
cardNumberElement.mount('#card-number-element');
var cardExpiryElement = elements.create('cardExpiry', {
style: style
});
cardExpiryElement.mount('#card-expiry-element');
var cardCvcElement = elements.create('cardCvc', {
style: style
});
cardCvcElement.mount('#card-cvc-element');
/*var postalCodeElement = elements.create('postalCode', {
style: style
});
postalCodeElement.mount('#postal-code-element');*/
function setOutcome(result) {
var successElement = document.querySelector('.success');
var errorElement = document.querySelector('.error');
successElement.classList.remove('visible');
errorElement.classList.remove('visible');
if (result.token) {
// In this example, we're simply displaying the token
successElement.querySelector('.token').textContent = result.token.id;
successElement.classList.add('visible');
// In a real integration, you'd submit the form with the token to your backend server
//var form = document.querySelector('form');
//form.querySelector('input[name="token"]').setAttribute('value', result.token.id);
//form.submit();
} else if (result.error) {
errorElement.textContent = result.error.message;
errorElement.classList.add('visible');
}
}
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
stripe.createToken(cardNumberElement).then(setOutcome);
});
<script src="https://code.jquery.com/jquery-2.0.2.min.js"></script>
<script src="https://js.stripe.com/v3/"></script>
<form action="" method="POST">
<input type="hidden" name="token" />
<div class="group">
<div class="card-container1">
<label>
<span class="title-card">Card number</span>
<div id="card-number-element" class="field"></div>
<span class="brand"><i class="pf pf-credit-card" id="brand-icon"></i></span>
</label>
</div>
<div class="card-details">
<div class="expiration">
<label>
<span class="title-card">Expiry date</span>
<div id="card-expiry-element" class="field"></div>
</label>
</div>
<div class="cvv">
<label>
<span class="title-card">CVC</span>
<div id="card-cvc-element" class="field"></div>
</label>
</div>
</div>
</div>
<button type="submit">Pay $25</button>
<div class="outcome">
<div class="error"></div>
<div class="success">Success! Your Stripe token is <span class="token"></span></div>
</div>
</form>
What I want to do:
Elements does not support collecting the cardholder's name at the moment. It focuses on collecting:
Card number
Expiration date
CVC
ZIP code (in some countries)
If you want to collect the cardholder's name you have to build your own field for the name and submit it to the API during token creation:
var card_name = document.getElementById('card_name').value;
stripe.createToken(card, {name: card_name}).then(setOutcome);
You can see a live example on jsfiddle here: https://jsfiddle.net/7w2vnyb5/
As I struggled like an idoit on this for a while. As of Feb 2019 you can add tokenData object with information on the details of the card. For Example:
let custData = {
name: 'Firstname Lastname',
address_line1: '21 Great Street',
address_line2: 'Shilloong',
address_city: 'Chicago',
address_state: 'Illinois',
address_zip: '12345',
address_country: 'US'
};
stripe.createToken(card, custData).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
If you're using "PaymentIntents", which you probably should be if you're EU based / SCA compliant, then the format for this has changed again slightly...
stripe.confirmCardPayment(
'{PAYMENT_INTENT_CLIENT_SECRET}',
{
payment_method: {
card: cardElement,
billing_details: {
name: 'Jenny Rosen'
}
}
}
).then(function(result) {
// Handle result.error or result.paymentIntent
});
stripe.confirmCardPayment docs:
https://stripe.com/docs/stripe-js/reference#stripe-confirm-card-payment
billing_details object docs:
https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
I use Meta-Data for custom fields such as cardholder name:
... create({
amount: myAmount,
currency: 'USD,
description: "Put your full discription here",
source: tokenid,
metedata: {any: "set of", key: "values", that: "you want", cardholder: "name"}
},
idempotency_key "my_idempotency_key"
)}
resource: https://stripe.com/docs/payments/charges-api#storing-information-in-metadata

Dgrid + Selection Issue

Still trying to work with Dgrid (0.4) and dojo (1.10), I have now another issue with the selection.
My web page contain a Dialog opened when you click on a button.
Inside this dialog, we have the following code which display a grid with data coming from a database through a Json HTTP page. This is working fine, even sorting and query filtering.
What I want to do know is to allow the user to double click on a row, get the selected row Id contains in the first column to update the form in the main page. I use the dgrid/selection for this. However, it always return the last row of the grid instead of the one the user selected.
The selection code is based on this :
http://dgrid.io/tutorials/0.4/hello_dgrid/
Any idea?
Thanks
<script language="javascript">
require
(
[
"dojo/_base/declare",
"dojo/_base/array",
"dgrid/OnDemandList",
"dgrid/OnDemandGrid",
"dgrid/Keyboard",
"dgrid/Selection",
"dgrid/Editor",
"dgrid/extensions/ColumnHider",
"dstore/Memory",
"dstore/RequestMemory",
"dojo/_base/lang",
"dojo/dom-construct",
"dojo/dom",
"dojo/on",
"dojo/when",
"dojo/query",
"dojo/store/Observable",
"dstore/Rest",
"dojo/_base/Deferred",
"dojo/store/Cache",
"dojo/domReady!",
],
function(
declare, arrayUtil, OnDemandList, OnDemandGrid, Keyboard, Selection, Editor, ColumnHider, Memory, RequestMemory, lang, ObjectStore, dom, on, when, query, Observable, Rest, Deferred
){
var fform = dom.byId("filterForm");
var ContactColumns = [
{ label: "", field: "contact_id", hidden: true, unhidable: true},
{ label: "Company Name", field: "company_name", unhidable: true },
{ label: "Contact Name", field: "contact_name", unhidable: true },
{ label: "Email", field: "contact_email", unhidable: true }
];
var ContactGrid=declare([OnDemandGrid, Keyboard, Selection,ColumnHider]);
var contactlist = new Observable(new Rest({ target: './ajax.contactsLoader.php' }));
var selection = [];
window.contactgrid = new ContactGrid(
{
className: "dgrid-selectors",
collection: contactlist,
maxRowsPerPage:10,
selectionMode: 'single',
cellNavigation: false,
columns: ContactColumns
}, "contacttable"
);
on(fform, "submit", function (event) {
var cpy_filter = fform.elements.fcompany_name.value;
var ct_filter = fform.elements.fcontact_name.value;
var email_filter = fform.elements.fcontact_email.value;
contactgrid.set('collection',contactlist.filter({contact_name: ct_filter, company_name: cpy_filter, contact_email: email_filter }));
contactgrid.refresh();
event.preventDefault();
});
contactgrid.on('dgrid-select', function (event) {
// Report the item from the selected row to the console.
console.log('Row selected: ', event.rows[0].data);
});
contactgrid.on('dgrid-deselect', function (event) {
console.log('Row de-selected: ', event.rows[0].data);
});
contactgrid.on('.dgrid-row:click', function (event) {
var row = contactgrid.row(event);
console.log('Row clicked:', row.data);
});
}
);
</script>
<div class="dijitDialogPaneContentArea" style="width:96%;margin-left:5px">
<form id="filterForm">
<div class="dijitDialogPaneActionBar" >
<button data-dojo-type="dijit.form.Button" type="submit">Filter</button>
<button
data-dojo-type="dijit.form.Button"
data-dojo-attach-point="submitButton"
type="submit"
>
Select
</button>
<button
data-dojo-type="dijit.form.Button"
data-dojo-attach-point="cancelButton"
>
Close
</button>
</div>
<div data-dojo-attach-point="contentNode" >
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcompany_name" id="fcompany_name" style="width:33%">
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcontact_name" id="fcontact_name" style="width:32%">
<input type="text" data-dojo-type="dijit.form.TextBox" name="fcontact_email" id="fcontact_email" style="width:33%">
<div id="contacttable">
</div>
</div>
</form>
</div>
Just found the reason.
the columns need to have a 'id' column called ID. I just change the 'contact_id' column to 'id' and it works fine.
thanks

Kendo UI Core Listview Edit Template with Autocomplete TextBox(Kendo Autocomplete)

How to use the Kendo UI Autocomplete textbox inside the Listview Edit Template??While trying to apply the autocomplete option the text box not taking it.The requirement also includes a server side filtering option.This needs to be implemented in an ASP.NET MVC5 Web Application.
I am working on Kendo UI for Jquery and I have implemented something similar. Idea behind the implementation is that you have to add the autocomplete when you are editing the ListView.
I am sharing the "Edit Template" and "ListView JS" below.
I found the idea here http://jsfiddle.net/F4NvL/
<script type="text/x-kendo-tmpl" id="editTemplate">
<div class="product-view k-widget">
<dl>
<dt>Product Name</dt>
<dd>
<label for="PAPC">Project Code<span class="k-icon k-i-star requiredstar" data-toggle="tooltip" title="Required"></span></label>
<input type="text" required name="PAPC" validationMessage="Hotel is required" data-bind="value: ProjectCode" />
<span class="k-invalid-msg" data-for="PAPC"></span>
</dd>
</dl>
<div class="edit-buttons">
<a class="k-button k-update-button" href="\\#"><span class="k-icon k-i-check"></span></a>
<a class="k-button k-cancel-button" href="\\#"><span class="k-icon k-i-cancel"></span></a>
</div>
</div>
var listView = $("#lvPA").kendoListView({
dataSource: datasrc,
template: kendo.template($("#template").html()),
editTemplate: kendo.template($("#editTemplate").html()),
edit: function (e) {
var model = e.model;
var item = $(e.item[0]);
var projectcode = item.find('[name="PAPC"]'); //Get your element
//Add a autocomplete here
projectcode.kendoAutoComplete({
valueTemplate: '<span>#:data.ProjectCode#</span>',
template: projectTemplate,
minLength: 3,
autoWidth: true,
dataTextField: "ProjectCode",
dataSource: new kendo.data.DataSource({
type: "GET",
serverFiltering: true,
transport: {
read: ProjectAPI,
parameterMap: function (data, type) {
return { filter: $('[name="PAPC"]').val() };
}
},
}),
height: 200
});
}
}).data("kendoListView");

Resources