Ember-Validations - Don't validate automatically - validation

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');
}
},
}
}
);

Related

How do I access another field's value in Joi validation?

How do I access another field value while I am validating a field?
export const validation = {
body: Joi.object({
name: Joi.string()
.required()
.min(2)
.max(20)
email: Joi
.string()
.required()
.email()
.pattern(new Regex()) // access value name here
.when('name', {
is: Joi.required(),
then: // access value of name here
}),
}),
}
In this case, I want to access the name field value in email field validation.
You can use the custom function to access the values of an object in the schema
export const validation = {
body: Joi.object({
name: Joi.string()
.required()
.min(2)
.max(20)
email: Joi
.string()
.required()
.email()
}).custom((user, helpers) => {
const { email, name} = user;
if (your regex validation on email) {
// if email validation failed
return helpers.message({
custom: `invalid email`
});
}
if (email !== `${name}#example.com`) {
// if name validation failed
return helpers.message({
custom: `email must be ${name}#example.com`
});
}
return user;
}),
}),
}

VueJS: Is there an easy way to validate email and password on client side based on the server side's validator?

I'm new to VueJS. I'm creating signup and login page and users are supposed to send the email and password to the back-end (I'm using Django) to check if the data is valid. I'd like to show error messages on form if one of them are not valid.
I saw some documentation about validation and seems like I have to write a bunch of validation code. Now I'm wondering if there's an easy way to do it.
I'd like to validate them based on the server side's validators.
Login.vue
export default {
data() {
return {
form: {
email: '',
password: '',
}
}
},
methods: {
onSubmit(event) {
event.preventDefault()
// validate the inputs here and shows error messages if they are not valid
const path = `http://127.0.0.1:8000/users/login/`
axios.post(path, this.form).then((resp) => {
location.href = '/'
})
.catch((err) => {
console.log(err)
})
}
}
}
Can anyone give me tips?
Yes, Here is the code you can follow.
In data make a reg object like this.
data(){
return{
email:null,
reg: /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/
}
},
add then in your submit method
if(this.email == null || this.email == '')
{
this.errorEmail = "Please Enter Email";
}
else if(!this.reg.test(this.email))
{
this.errorEmail = "Please Enter Correct Email";
}

sequelize custom validator

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,
});

Meteor SimpleSchema: prevent form submission using asynchronous custom validation

I have implemented a custom validation function using the example referenced in the SimpleSchema documentation for validating the uniqueness of a username. In the example, an asynchronous call is made and a custom validation message is displayed if the username is found to already exist.
There is a note, that indicates that if all of the form fields are valid, the form will be submitted, however user creation will fail due to the "unique: true" requirement specified in the schema. Here is the relevant portion of the code from the example docs:
username: {
type: String,
regEx: /^[a-z0-9A-Z_]{3,15}$/,
unique: true,
custom: function () {
if (Meteor.isClient && this.isSet) {
Meteor.call("accountsIsUsernameAvailable", this.value, function (error, result) {
if (!result) {
Meteor.users.simpleSchema().namedContext("createUserForm").addInvalidKeys([{name: "username", type: "notUnique"}]);
}
});
}
}
}
In my case, I have the code working where I am testing if an activation code is valid, I even get the interface to display the error, however since there is no other "schema" failure, the form submits, despite the invalid response... do I need to manually prevent form submission (i.e. using jQuery), or is there something in SimpleSchema I should use instead?
activationCode: {
type: String,
label: "Activation Code",
max: 200,
min: 10,
regEx: /^(?=.*[A-Z])(?=.*\d).+$/,
custom: function() {
if (Meteor.isClient && this.isSet) {
Meteor.call("validateActivationCode", this.value, function(error, result) {
if (result && !result.isValid) {
Clients.simpleSchema().namedContext("signupForm").addInvalidKeys([{
name: "activationCode",
type: "notValid"
}]);
return false;
}
});
}
}
}
Thank You

Kendo grid data("kendoValidator").validate() method always returns true

$("#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 });

Resources