Ajv return valid schema if schema has required set and data is empty string - ajv

Hi I have just started to learn AJV and I am a bit confused on how it handles required fields. I am working on an already built project and maybe some of the configuration is not needed for the current use case, or is done wrong.
I am using AJV verion 5.5.1.
Here is my code:
const opt = {
$data: true, allErrors: true, verbose: true, unknownFormats: ['int32', 'int64', 'double']
};
opt['v5'] = true;
const validator = withKeywords(new Ajv(opt), ['switch', 'if']);
withError(this.validator);`enter code here`
const schema = {
'required': [
'name'
],
'type': 'object',
'properties': {
'name': {
'type': 'string'
}
}
}
const data = {
name: ''
}
const isValid = validator.validate(schema, data);
Now this will set the isValid variable to true and validator.errors has no errors which kind of confuses me a bit. Since what i hoped would happen was it to be false because at the schema level I am setting in the required property the 'name' key.
I also tryed setting data.name = null an I am getting isValid false with error that makes sense to me because I am setting the type to string at the schema level, but it is not a validation required error. I want be able to diferentiate beetween a required error and a type error.
How can I make the validator return false if a property does not have a value?

Related

Upsert ref documents when pushing to array in Express

I have a Candidate schema with an array of refs to an Endorser schema. Like so:
const CandidateSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
endorsements: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Endorser'
}]
});
const EndorserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
});
I receive endorsements in the form of an array of strings (i.e., the endorser's name). I want to iterate through that array and retrieve the _id of each from the Endorser model or upsert a new one if it doesn't exist. I then want to push those refs onto the existing candidate instance.
The following code works, but I really don't feel comfortable modifying the candidate instance in-memory. Having to do the promise resolution separately also seems weird.
const endorsementPromises = endorsements.map(async endorser => {
let endorserObj = await Endorser.findOneAndUpdate({name: endorser}, {name: endorser}, {upsert: true, new: true});
return endorserObj._id;
});
const endorsementArray = await Promise.all(endorsementPromises);
candidate.endorsements = candidate.endorsements.concat(endorsementArray);
await candidate.save();
I have tried using findOneAndUpdate with $push and $each. However, this only returns an error and doesn't update the document.
Candidate.update(
{id: candidate._id},
{$push: {
endorsements: {
$each: endorsementArray
}
}}
);
// the error
Error: {"n":0,"nModified":0,"ok":1}
I'm not sure why $push and $each aren't updating the document.
Any guidance would be really appreciated.
Try using $addToSet instead of $push. Also, it seems like you should be matching on _id instead of id in your update.

omitNull not working on primaryKey column in Sequelize

I have a SQL server database with a table which auto inserts a guid in each row when a record is added. This column is the primary key for the table and never needs a value to be supplied to it as it's automatic.
The trouble is that Sequelize is sending NULL for this column every time I do a .create({emailAddress:"test#test.com"}) call which is causing an error in the database (because nulls aren't allowed, obviously).
I've tried adding omitNull at the top level and at the "call" level and neither of them work , unless I remove the primary key and then it doesn't send a NULL. So it seems that Sequelize thinks that if something is the primary key then it must send a value, not understanding that the SQL SERVER database is going to handle insertion of that value.
Anybody know a workaround?
// Model
module.exports = function (sequelize, DataTypes) {
const Player = sequelize.define('Player', {
playerId: {
primaryKey: true,
type: DataTypes.STRING
},
emailAddress: {
type: DataTypes.STRING
}
}, {
timestamps: false
});
return Player;
};
// Create a row
let newPlayer = {
emailAddress:'test#test.com'
}
Player.create(newPlayer, {omitNull:true}).then(function(player){
console.log("player", player)
}).catch(function(error){
console.log("error", error)
})
Adding defaultValue and allowNull should do the job
playerId: {
primaryKey: true,
defaultValue: '',
allowNull: false,
}

Sencha Touch 2.3: Remove validations from hidden form fields

I am doing form validations in Sencha Touch 2.3. My model looks like following.
Ext.define('net.omobio.dialog.dialogcc.model.StockTransferDetails', {
extend: 'Ext.data.Model',
config: {
fields: ['to_msisdn','to_profile_id','transfer_lob','transfer_item_status','transfer_product','transfer_qty','transfer_req_type','transfer_item_type','transfer_pack_type'],
validations: [
{ type: 'presence', field: 'to_msisdn' },
{ type: 'presence', field: 'to_profile_id' },
{ type: 'exclusion', field: 'transfer_lob', list: ['null'] },
{ type: 'exclusion', field: 'transfer_req_type', list: ['null'] },
{ type: 'exclusion', field: 'transfer_item_type', list: ['null'] },
{ type: 'exclusion', field: 'transfer_pack_type', list: ['null'] }
]
}
});
Following is a code segment that I use in my controller to remove validations from hidden form fields but no luck.
var form1 = me.getStockTransferRequestPage();
var model = Ext.create("net.omobio.dialog.dialogcc.model.StockTransferDetails", form1.getValues());
// validate form fields
var errors = model.validate();
if (!errors.isValid()) {
// loop through validation errors and generate a message to the user
errors.each(function (errorObj){
//errorString += errorObj.getField() + " " + errorObj.getMessage();
console.log('7777777777777777777 '+errorObj.getField());
if (!Ext.getCmp(errorObj.getField().toString()).isHidden()) {
var s = Ext.String.format('field[name={0}]',errorObj.getField());
form1.down(s).addCls('invalidField');
}
});
Ext.Msg.alert('','stock_transfer.errors.required_fields_empty');
}
I would be much appreciated if anyone could help me to solve this.
Thank you
so there are multiple ways to achieve this, my preference even though some folks won't like it, but it will always work.
I did the following override to solve this problem, tried my best not to affect the normal flow of validation.the first two overrides have to be added somewhere to your overrides folder, you only have to add them once for the whole app.
Ext.Define('Ext.form.field.BaseOverride', {
override: 'Ext.form.field,Base',
/* traverse up and look for a hidden Parent/Ancestor */
isParentHidden: function () {
return this.up('[hidden=true]');
}
/* override isValid basic method to consider skipValidateWhenHidden property, when skipValidateWhenHidden is set to true code should check if the elementor it's Parent/Ancestors is hidden */
isValid: function () {
var me = this,
disabled = me.disabled,
isHidden = me.isHidden(),
skipValidateWhenHidden = !!me.skipValidateWhenHidden,
validate = me.forceValidation || !disabled,
isValid = validate ? me.validateValue(me.processRawValue(me.getRawValue())) : disabled;
if (isValid || !skipValidateWhenHidden) {
return isValid;
}
if (skipValidateWhenHidden) {
isHidden = isHidden ? true : me.isParentHidden();
if (isHidden) {
return skipValidateWhenHidden;
}
}
return isValid;
}
});
and eventually you'll be able to do the following, which is set the property to true on any field so if its not visible for the user, it will survive validation
{
itemId: 'City',
cls: 'AddressCity',
xtype: 'textfield',
emptyText: emptyCityText,
skipValidateWhenHidden: true,
},
another approach is to add a show()/Hide() listener on the fields container to enable/disable the children, disabling the fields would make them skip validation, but i'm not a big fan of managing button states and wiring listeners.
Note
Ext.getCmp() takes component id
errorObj.getField().toString() returns model field name, It won't
return id of the component (hidden) field.
So if model field name matches with hidden field id, It will work. Otherwise it won't work.

Backbone.validation not working on save

I have a simple model using the Backbone.Validations plugin.
var LocationModel = Backbone.Model.extend({
validation: {
location_name: {
required : true,
msg : 'A name is required for the location'
}
} // end validation
});
var test = new LocationModel();
test.url = 'http://link-goes-here';
test.save();
It appears that on the save event, it's going ahead and saving my empty model even though the attribute "location_name" is required?
I just did a bunch of testing and the only way I could get it to consistently not send a request was by also creating defaults on the model:
var LocationModel = Backbone.Model.extend({
defaults: {
location_name: null
},
validation: {
location_name: {
required: true,
msg: 'A name is required for the location'
}
} // end validation
});
var test = new LocationModel();
test.on('validated', function() {
console.log(arguments);
});
test.url = '/echo/json';
test.save();
Here's a fiddle. If you comment out the defaults, it sends a request initially, even though the validated event is saying that it's invalid. And then fires validated again without sending the request.

extjs change default value of store

Let us assume, there is a JsonStore :
SomeStore = Ext.extend(Ext.data.JsonStore, {
constructor: function(cfg) {
cfg = cfg || {};
OrdersStore.superclass.constructor.call(this, Ext.apply({
storeId: 'someStore',
url: 'someUrl',
root: 'rows',
fields: [
{
name: 'someId'
defaultvalue : '100'
}
]
}, cfg));
}
});
How can I do this:
new SomeStore().getFieldByname('someId').setDefaultvalue = '73'
What is the proper syntax for this?
someStore.fields.item('someId').defaultValue = 73;
"someStore.fields" comes up as "null" for me (version 6.2.0).
While it may be possible to go through the store directly to do this, going through the model is working well to update a field's defaultValue just before creating a new record:
someStore.getModel().getField('someId').defaultValue = 73
NOTE: I've found this only works if the defaultValue parameter was used when the field was defined in the first place. If not defined initially, even as 'null', setting it later does not work for me.

Resources