I would like to create custom field validator with reference to existing field. What I did is to create a custom validator:
const User = sequelize.define('User', {
postalCode: {
type: DataTypes.STRING
},
country: DataTypes.STRING,
}, {
validate: {
wrongPostalCode() {
if (this.postalCode && this.country) {
if (!validator.isPostalCode(String(this.postalCode), this.country)) {
throw new Error('Wrong postal code')
}
}
}
}
});
User.associate = (models) => {
// TO DO
};
return User;
};
As you can see below in error message, we are getting this validator but in the row "path" there is validator name. I would like to change it for example to "postalCode" or somehow connect it with one field from the model. It is very important for me as this is related to Front-End and to parse it to correct form control.
enter image description here
Is there any way to do it?
Thank you in advanced :)
Have you tried to use a custom validator for the field instead? I haven't tried the following piece of code but should work and link the validator to the postalCode field.
const User = sequelize.define('User', {
postalCode: {
type: DataTypes.STRING,
validate: {
wrongPostalCode(value) {
if (this.country) {
if (!validator.isPostalCode(String(this.postalCode), this.country)) {
throw new Error('Wrong postal code');
}
}
}
}
},
country: DataTypes.STRING,
});
Related
I am trying to create a custom controller to update the user profile.
I created the routing file and the corresponding controller.
Routing file: server/src/api/profile/routes/profile.js
module.exports = {
routes: [
{
method: 'GET',
path: '/profile',
handler: 'profile.getProfile',
},
{
method: 'PUT',
path: '/profile',
handler: 'profile.updateProfile',
},
]
}
Controller: src/api/profile/controllers/profile.js
async updateProfile(ctx) {
try {
const { id } = ctx.state?.user;
const user = strapi.query('admin::user').update({
where: { id },
data: {
username: "testUsername"
}
})
ctx.body = "User updated"
} catch(error) {
ctx.badRequest("Something went wrong", { error })
}
},
The above code returns "User updated", but the username does not update. I am executing the PUT call with a correct Bearer authorisation token and the user permissions for that user are set to enable "updateProfile".
Oddly enough, the same code, when changed to update a different API item, works perfectly fine:
async updateArticle(ctx) {
try {
const { id } = ctx.state?.user;
const article = strapi.query('api::article.article').update({
where: { author: id },
data: {
title: "New title"
}
})
ctx.body = article
} catch(error) {
ctx.badRequest("Something went wrong", { error })
}
},
I am also confused by different syntaxes appearing in the official Strapi documentation, for example some docs mention:
strapi.query('admin::user').update({ id }, data)
But in other places in the documentation its:
strapi.plugins['users-permissions'].services.user.update({ id });
And then elsewhere:
strapi.query('user', 'users-permissions').update(params, values);
Another question is: do I need to sanitise the input / output in any way? If yes, how? Importing sanitizeEntity from "Strapi-utils" doesn't work, but it's mentioned in several places on the internet.
Additionally, I cannot find a list of all ctx properties. Where can I read what is the difference between ctx.body and ctx.send?
The lack of good documentation is really hindering my development. Any help with this will be greatly appreciated.
I have a string field IsEnabled, it’s string. Value can be Yes, No or null. I am binding this column to grid column. It’s working as expected. But I want to show this on UI as checkbox. For value Yes, it should be checked or No or null it should be unchecked. And user can check/uncheck, based on user’s action. Yes or NO will be inserted in database.
I couldn’t find proper way of doing this, so what is the best way to handle this scenario?
I have tried by by adding one more bool field and setting it based on value Yes, No or null. And binding this field to grid.
But I am looking for a clean approach
You can use the column template (documentation) to return a checkbox where the value is checked when the record's IsEnabled is Yes.
Then in the dataBound event of the grid (documentation) you would setup the event binding for the checkbox to get when the value changed.
Here is an example:
$('#grid').kendoGrid({
columns: [
{
field: 'Name'
},
{
field: 'name',
template: function(dataItem) {
var checkbox = $('<input />', {
checked: dataItem.IsEnabled === 'Yes',
type: 'checkbox'
});
return checkbox.prop('outerHTML');
}
}
],
dataSource: [
{
Id: 1,
Name: 'Person1',
IsEnabled: 'Yes'
},
{
Id: 2,
Name: 'Person2',
IsEnabled: 'No'
},
{
Id: 3,
Name: 'Person3',
IsEnabled: 'No'
}
],
dataBound: function(e) {
e.sender.table.on('change', 'input[type="checkbox"]', function() {
var checked = this.checked;
// send your AJAX request
});
}
});
Fiddle: https://dojo.telerik.com/igiTASAc
As I was looking for a Kendo MVC solution, So I have implemented it like the below.
Declare the property like this.
[UIHint("DropDownTemplate")]
public IsAllowedCls IsAllowed { get; set; }
public class IsAllowedCls
{
public int IsAllowedKey { get; set; }
public string IsAllowedValue { get; set; }
}
Add view under Views\Shared\EditorTemplates create the view named as DropDownTemplate with below content
#model FxTrader.Models.IsAllowedCls
#(Html.Kendo().DropDownList()
.Name("DropDownTemplate")
.DataValueField("IsAllowedKey")
.DataTextField("IsAllowedValue")
.BindTo((System.Collections.IEnumerable)ViewData["IsAllowedData"])
)
In the controller action method, add the below code.
ViewData["IsAllowedData"] = new List<IsAllowedCls>() { new IsAllowedCls { IsAllowedKey = 1, IsAllowedValue = "Yes" },
new IsAllowedCls { IsAllowedKey = 0, IsAllowedValue = "No" } };
createPaymentMethod of Stripe not working in Laravel and Vue stripe element. Here is my code
import { Card, createToken, createPaymentMethod } from 'vue-stripe-elements-plus';
components : {
stripeCard : Card
},
methods : {
pay() {
createToken({
name : this.name,
street_line1 : this.street,
street_country : this.selectedCountry,
street_zip : this.postalCode
})
.then((data) => {
createPaymentMethod('card', {
card: data.token.card.id, // token from createToken (without any params)
billing_details: {
name: this.name, // cardholder name
email: this.email,
address: { // address fetched from algolia places
line1: this.street,
country: this.selectedCountry,
city: this.city,
postal_code: this.postalCode,
},
}
})
})
}
}
But it shows error TypeError: Object(...) is not a function
I don't get where my problem is. Any help would be appreciable. Thanks in advance.
I am using this package
https://www.npmjs.com/package/vue-stripe-elements-plus
There is no need to create both a payment method and a token. The PaymentMethods API can be thought of as a newer version of the Tokens API (1). So you can simplify your code to:
methods : {
pay() {
createPaymentMethod('card', {
billing_details: {
name: this.name, // cardholder name
email: this.email,
address: { // address fetched from algolia places
line1: this.street,
country: this.selectedCountry,
city: this.city,
postal_code: this.postalCode,
},
}
})
}
}
*Note, I removed the card: data.token.card.id line entirely. This should be unnecessary since the library you're using adds a reference to the Card element for you automatically as you can see here:
https://github.com/fromAtoB/vue-stripe-elements/blob/ede16058193e2440dfd5a7cb7af17450d52e234b/src/stripeElements.js#L68
(1) https://stripe.com/docs/payments/payment-methods
I am using ember-validations to validate a model in a form.
If I create the record with createRecord the instance of the model is already validated and therefore the form already shows validations errors before the user inputs values.
I just want to validate the model before submitting the form. Is there a way?
You need to add a conditional validator ('if' or 'unless') and activate it only when submitting the form.
Here is a quick example: http://jsbin.com/letujimu/1/edit?html,js,output
There is another alternative to ember-validations. ember-model-validator, with this addon you decide when to validate. By including Ember-model-validator's mixin into your model, this will add a validate function to your model, it is a synchronous function which returns either true or false.
There is support for all these validations:
Presence
Acceptance
Absence
Format
Length
Email
Color
ZipCode
Subdomain
URL
Inclusion
Exclusion
Numericality
Match
Password
CustomValidation
Relations
Example:
// Your model
import Validator from '../mixins/model-validator';
export default DS.Model.extend(Validator, {
email: DS.attr('string'),
password: DS.attr('string'),
passwordConfirmation: DS.attr('string'),
validations: {
email: {
presence: true,
email: { message: 'is not a valid email' }
},
password: {
presence: true,
length: {
minimum: 6
}
},
passwordConfirmation: {
presence: true,
match: 'password'
}
}
});
import Ember from 'ember';
export default Ember.Route.extend(
{
actions: {
saveFakeModel: function() {
var _this = this,
fakeModel = this.get('model');
if(fakeModel.validate()){
fakeModel.save().then(
// Success
function() {
// Alert success
console.log('ooooh yeah we just saved the FakeModel...');
},
// Error handling
function(error) {
// Alert failure
console.log('There was a problem saving the FakeModel...');
console.log(error);
}
);
}else{
fakeModel.get('errors');
}
},
}
}
);
$("#mygrid").kendoValidator().data("kendoValidator").validate() method always returns true even if there are validation errors for some of the input fields in the grid. On first time load the validation works fine but during edit the next time it does not show the tooltip, please help me resolve this issue.
I have added a validation template using schema of the grid:
schema: {
model: {
id: "AuctionID",
fields: {
AuctionID: {
editable: false,
type: "number"
},
AuctionName: {
type: "string",
validation: {
required: { message: "An Auction Name is Required!" },
validateAuctionName: function (input) {
if (input.attr("data-bind") == "value:AuctionName") { // check if this is the element to validate
alert(input.val().length);
if (input.val().length > 10) {
input.attr("data-validateAuctionName-msg", "AuctionName can only have a maximum of 10 characters.");
return false;
}
else
return true;
}
return true;
}
}
}
}
}
}
The method you are using is not triggering validation as it interrogates "this" and validates it if it is a kendo widget with validation enabled.
I found this way to force validation - get hold of model and trigger change on property you want to validate:
model.trigger("set", { field: "FinishTime", value: model.FinishTime });