Kendo UI Grid validation when creating a new row - javascript

Currently I'm looking to validate new created row before saving changes,
schema is not working to enforce the rules on the created row.
I need to let the user know what fields are required if he tried to save with an error message.
This example has already custom validation ,you can see it in the schema ,the problem it's not forcing validation before submitting to the server.
var gResult = new kendo.data.DataSource({
read:,
update:,
create:,
schema: {
model: {
id: "Id",
fields: {
Id: { type: 'number' },
Color: { type: 'string', defaultValue: "#000" },
Name: {type: 'string', validation: { required: true } },
Address1: { validation: { required: true } },
City: { validation: { required: true } },
Country: { validation: { required: true }, defaultValue: "Deutchland" },
PostalCode: { type: 'number', validation: { required: true } },
Emails: {
type: 'string',
validation: {
required: { message: "Email ID Required." },
validateEmailFormat: function (input) {
if (input.attr("data-bind") == "value:Email") {
input.attr("data-validateEmailFormat-msg", "Email format invalid.");
return checkEmail(input.val());
}
return true;
}
}
}
}
}
});
$("#gridResult").kendoGrid({
columns: GridColumns.Columns,
dataSource: gResult,
navigatable: true,
sortable: true,
height: 1000,
filterable: true,
pageable: GridProp.Pageable,
editable: true, toolbar: ["create", "save"] });

Related

Updating the field of a nested object property inside an array of objects in mongodb

I have created the following schema in MongoDB. It is a customer schema with a sub-schema for storing the transactions. Each transaction is an object and each object(a transaction) contains a field called "transactionDetails", which is an object as well.
const transactionSchema = new Schema(
{
transactionType: {
type: String,
},
transactionDetails: {
transferredFrom: {
type: String,
default: "",
},
transferredTo: {
type: String,
default: "",
},
balance:{
type: Number,
default:0,
min: 0,
},
amount:{
type:Number,
default:0
}
},
},
{
timestamps: true,
}
);
const customerSchema = new Schema(
{
name: {
type: String,
required: [true, "Please provide a customer name"],
},
dob: {
type: Date,
required: [true, "Please provide a Date of Birth"],
},
address: {
type: String,
default: "India",
},
accNo: {
type: String,
required: true,
default: mongoose.Types.ObjectId,
},
email: {
type: String,
required: [true, "Please provide an email address"],
},
phone: {
type: String,
required: [true, "Please provide a phone number"],
},
transactions: [transactionSchema],
currentBal: {
type: Number,
required: [true, "Please provide valid balance"],
default: 0,
min:0
},
},
{
timestamps: true,
}
);
All I want to do is to set the value of a field to an existing field in the document while updating it. I want to set the value of "balance" field to the current updated value of the "currentBal" after the "currentBal" field has been updated.
The problem is that the no matter what I did, the value of "balance" field always set to default value without throwing any error
Customer.findOneAndUpdate(
{ accNo: id },
{
$inc: { currentBal: Number(amount),
},
$push: {
transactions: {
transactionType: "deposit",
transactionDetails: {
transferredFrom: "Self",
transferredTo: "Self",
balance:{currentBal} ,
amount: Number(amount),
},
},
},
},
(err, customer) => {
if (err !== null && err.name === "ValidationError") {
res.json({ message: err._message });
} else {
console.log("Balance has been updated successfully");
// console.log(customer.currentBal);
res.redirect(`/customers/${id}`);
}
}
);

meteor cannot validate user profile schema

I created in meteor.js a user profile edit page based on autoform and simpl-schema packages. I also added Tracker to schema.
I wanted to make field Profile.Username required but it's validate when field is empty. This field is also unique and handling this property works good.
Also Email field is required and there Tracker works good.
Here is my code:
users.js
import { Mongo } from 'meteor/mongo';
import { Tracker } from 'meteor/tracker';
import SimpleSchema from 'simpl-schema';
SimpleSchema.extendOptions(['autoform']);
Schema.User = new SimpleSchema({
emails: {
type: Array,
optional: true
},
'emails.$': {
type: Object,
optional: true,
},
'emails.$.address': {
type: String,
regEx: SimpleSchema.RegEx.Email
},
'emails.$.verified': {
type: Boolean,
optional: true,
autoform: {
type: 'boolean-checkbox'
}
},
createdAt: {
type: Date,
autoValue: function() {
return new Date();
},
autoform: {
type: 'hidden'
}
},
profile: {
type: Schema.UserProfile,
optional: true
},
services: {
type: Object,
optional: true,
blackbox: true,
autoform: {
type: 'hidden'
}
}
}, {tracker: Tracker});
Meteor.users.attachSchema(Schema.User);
Meteor.users.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
profile.js
import { Mongo } from 'meteor/mongo';
import { Tracker } from 'meteor/tracker';
import SimpleSchema from 'simpl-schema';
SimpleSchema.extendOptions(['autoform']);
Schema = {};
Schema.UserProfile = new SimpleSchema({
username: {
type: String,
label: 'Username',
unique: true,
},
firstName: {
type: String,
optional: true
},
lastName: {
type: String,
optional: true
},
birthday: {
type: Date,
optional: true,
autoform: {
type: 'bootstrap-datepicker',
datePickerOptions: {
autoclose: true
}
}
},
gender: {
type: String,
optional: true,
autoform: {
type:'select-radio',
options: function () {
return [
{ label: 'Male', value: 'Male'},
{ label: 'Female', value: 'Female'},
];
},
}
}
}, {tracker: Tracker});
and ProfileEdit.html
<template name="ProfileEdit">
{{> Header}}
{{> SideNav}}
<div class="main-layout">
<legend>Update Profile</legend>
{{#if Template.subscriptionsReady}}
{{# autoForm id="profileEdit" collection="Meteor.users"
doc=currentUser type="update"}}
{{> afObjectField name="emails.0"}}
{{> afObjectField name="profile"}}
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
{{/autoForm}}
{{/if}}
</div>
</template>
Please, help me.

Issue when login and register with Facebook in Meteor

I'm trying to use Facebook to connect and register into my Meteor.js application. In my login template I put a button to do this. I call the function Meteor.loginWithFacebook() but it doesn't work... I'm guessing that Meteor try to create a new user and that it doesn't find the username information but I don't know how to manage that.
My handler to call the login :
'click #facebook-login': function(event) {
Meteor.loginWithFacebook({}, function(err){
if (err) {
throw new Meteor.Error("Facebook login failed");
Materialize.toast('Echec de connexion!', 4000);
}
else {
Router.go(Utils.pathFor('home'));
Materialize.toast('Bon retour parmis nous ' + Meteor.user().username + ' !', 5000);
}
});
}
The error I have :
I20160428-12:44:56.099(2)? Exception while invoking method 'login' Error: Nom d'utilisateur is required
I20160428-12:44:56.100(2)? at getErrorObject (packages/aldeed_collection2-core/lib/collection2.js:437:1)
I20160428-12:44:56.101(2)? at [object Object].doValidate (packages/aldeed_collection2-core/lib/collection2.js:420:1)
I20160428-12:44:56.101(2)? at [object Object].Mongo.Collection. (anonymous function) [as insert] (packages/aldeed_collection2-core/lib/collection2.js:173:1)
I20160428-12:44:56.101(2)? at AccountsServer.Ap.insertUserDoc (packages/accounts-base/accounts_server.js:1250:25)
I20160428-12:44:56.101(2)? at AccountsServer.Ap.updateOrCreateUserFromExternalService (packages/accounts-base/accounts_server.js:1386:20)
I20160428-12:44:56.102(2)? at [object Object].Package (packages/accounts-oauth/oauth_server.js:55:1)
I20160428-12:44:56.103(2)? at packages/accounts-base/accounts_server.js:464:32
I20160428-12:44:56.103(2)? at tryLoginMethod (packages/accounts-base/accounts_server.js:241:14)
I20160428-12:44:56.103(2)? at AccountsServer.Ap._runLoginHandlers (packages/accounts-base/accounts_server.js:461:18)
I20160428-12:44:56.103(2)? at [object Object].methods.login (packages/accounts-base/accounts_server.js:524:27)
I20160428-12:44:56.129(2)? Sanitized and reported to the client as: Nom d'utilisateur is required [400]
User schema :
Globals.schemas.UserProfile = new SimpleSchema({
firstName: {
type: String,
regEx: /^[a-zA-Z-]{2,25}/,
optional: true,
label: "Prénom"
},
lastName: {
type: String,
regEx: /^[a-zA-Z-]{2,25}/,
optional: true,
label: "Nom"
},
birthDay: {
type: Date,
optional: true,
label: "Date de naissance",
min: new Date("1900-01-01T00:00:00.000Z"),
autoform: {
value: new Date("1900-10-18T00:00:00.000Z")
}
},
gender: {
type: String,
allowedValues: ['M', 'F'],
optional: true,
label: "Genre",
autoform: {
options: [
{
label: "Homme",
value: "M"
},
{
label: "Femme",
value: "F"
}
],
firstOption: "(Veuillez sélectionner une réponse)"
}
},
level: {
type: Number,
autoValue: function () {
if (this.isInsert) {
return 1;
}
},
autoform: {
omit: true
},
min: 0,
max: 1000,
label: "Niveau"
},
picture: {
type: String,
optional: true,
autoform: {
omit: true
},
label: "Photo"
}
});
// Schéma principal
Globals.schemas.User = new SimpleSchema({
username: {
type: String,
regEx: /^[a-z0-9A-Z_]{3,30}$/,
label: "Nom d'utilisateur"
},
password: {
type: String,
label: "Mot de passe",
optional: true,
autoform: {
afFieldInput: {
type: "password"
}
}
},
confirmation: {
type: String,
label: "Confirmation",
optional: true,
custom: function(){
if(this.value !== this.field('password').value){
return "passwordMissmatch";
}
},
autoform: {
afFieldInput: {
type: "password"
}
}
},
emails: {
type: [Object],
optional: false,
label: "Adresses Email"
},
"emails.$.address": {
type: String,
regEx: SimpleSchema.RegEx.Email,
label: "Adresses Email"
},
"emails.$.verified": {
type: Boolean,
optional: true,
autoform: {
omit: true
}
},
createdAt: {
type: Date,
autoValue: function () {
if (this.isInsert) {
return new Date;
} else {
this.unset();
}
},
autoform: {
omit: true
}
},
profile: {
type: Globals.schemas.UserProfile,
optional: true
},
services: {
type: Object,
optional: true,
blackbox: true,
autoform:{
omit: true
}
},
roles: {
type: Object,
optional: true,
blackbox: true,
autoform: {
omit: true
}
}
});
Thank's for any help !
The problem is that your schema requires Meteor.users to have a username field, which they don't contain by default. You can, however, generate this field by taking their name name from the Facebook profile.
Accounts.onCreateUser(function(options, user) {
user.username = user.services.facebook.name;
return user;
});
http://docs.meteor.com/#/full/accounts_oncreateuser

many-to-many relationship - populating related data in query - Keystonejs

I am working on a keystonejs project here and am running into a problem with relationships between two models.
I have the below two models:
User model:
User.add({
name: { type: Types.Name, required: true, index: true },
email: { type: Types.Email, initial: true, required: true, index: true },
number: { type: Types.Number, index: true },
password: { type: Types.Password, initial: true, required: true }
}, 'Permissions', {
isAdmin: { type: Boolean, label: 'Can access Keystone', index: true },
}, 'Groups', {
groups: {type: Types.Relationship, ref: 'Group', many: true }
});
And I have a Group model
Group.add({
name: { type: String, required: true, index: true },
description: { type: String, initial: true, required: true, index: true}
});
I have a aggregate function that basically pulls all of the groups that have users in it
User.model.aggregate({$group:{'_id':'$groups'}}).exec(function(err,data){
console.log(data);
});
My problem is that the above aggregate only shows me my groups by their _id values and not their names.
How could I populate and show the names in the front end? Obviously the id's are necessary on the back end to reference but to the front end users that won't work.
Thanks
You can create what you want pretty easily so don't be discouraged. You just need a heads up on the '.populate()' function in mongoose. See example below.
User Model (slightly tidied - I removed the (strange?) nesting)
User.add({
name: { type: Types.Name, required: true, index: true },
email: { type: Types.Email, initial: true, required: true, index: true},
number: { type: Types.Number, index: true },
password: { type: Types.Password, initial: true, required: true },
isAdmin: { type: Boolean, label: 'Can access Keystone', index: true },
groups: {type: Types.Relationship, ref: 'Group', many: true }
});
Group Model -- note the Group.relationship({}) option I've added near the bottom for admin convenience (shows users which reference that group on the backend)
Group.add({
name: { type: String, required: true, index: true },
description: { type: String, initial: true, required: true, index: true}
});
Group.relationship({ ref: 'User', path: 'users', refPath:'Groups'});
Controller getting a list of users with all their corresponding group information
view.on('init', function(next) {
keystone.list('User').model.find()
.populate('groups')
.exec(function(err, users) {
if(err) {
console.log(err);
return next(err);
} else {
locals.data.users = users;
next(err);
}
});
});
Controller getting Users within a specific group to display on the frontend (you need the group ID first)
view.on('init', function(next) {
keystone.list('User').model.find()
.where('Groups').in([array, of, group, ids])
.populate('groups')
.exec(function(err, users) {
if(err) {
console.log(err);
return next(err);
} else {
locals.data.users = users;
next(err);
}
});
});
locals.data.users would return like this in each case:
[
{
_id: '',
name: '',
...
groups: [
{
_id: '',
name: ''
...
}
]
}
]

errorPlacement can not be validate in first call but work fine in second click

using following function for validating but cant be work fine in first time but work fine in second time.
second function is used for validator and its not working fine when i first click the button but its work fine second time please help.
function saveValue(){
if (validateFormset().form()) { // validation perform
$('form#vendorActionForm').attr({methos: 'POST'});
$('form#vendorActionForm').attr({action: 'vendorAddressCreateUpdate.htm'});
$('form#vendorActionForm').submit();
}else{
$(".textMessgeClass").text("Please fill the highlighted field/s");
$(".textMessgeClass").addClass('errorClass');
$(".textMessgeClass").fadeIn("slow");
$(".textMessgeClass").delay(2000).fadeOut(2000);
}
}
function validateFormset(){
var validator = $("#vendorActionForm").validate({
rules: {
accountType: {
required:true
},
addressRank: {
required:true
},
street: {
required:true
},
city: {
required:true
},
state: {
required: true,
accept: "[a-zA-Z]+",
minlength: 2
},
region: {
required: true
},
zipCode: {
required: true,
rangelength: [3, 5]
},
contactName: {
required: true
},
mobile: {
required: false,
number: true,
minlength: 10
},
email: {
required: true,
email: true
},
email2: {
required: false,
email: true
},
email3: {
required: false,
email: true
}
},
errorPlacement: function(error, element) {
$(element).filter(':not(.valid)').addClass("addressErrorClass");
},
success: function(error) {
$("#vendorActionForm").find('.valid').removeClass("addressErrorClass");
}
});
alert('AAAA');
alert(validator);
return validator;
}

Categories