Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aurelia-Validation: My approach at centralizing the validation and still being able to use custom-validation
import moment from 'moment';
export function isValidDate(fmt) {
let dateFormat = fmt || 'MM/DD/YYYY';
this.passes((newValue) => {
let mmt = moment(newValue, dateFormat);
return mmt.isValid() && mmt.format(dateFormat) === newValue;
});
return this;
}
import {inject, transient} from 'aurelia-framework';
import {ValidationGroup} from 'aurelia-validation';
import {isValidDate} from 'framework/validation/is-valid-date';
@transient()
@inject()
export class UserModel {
constructor() {
ValidationGroup.prototype.isValidDate = isValidDate;
}
firstName = "";
lastName = "";
email = "";
password = "";
confirmPassword = "";
dob = "";
gender = "";
validator(item, validation) {
return validation.on(item)
.ensure('firstName')
.isNotEmpty()
.ensure('lastName')
.isNotEmpty()
.ensure('email')
.isNotEmpty()
.isEmail()
.ensure('password')
.isNotEmpty()
.ensure('confirmPassword')
.isNotEmpty()
.ensure('dob')
.isNotEmpty()
.isValidDate()
.withMessage('not valid date')
.ensure('password')
.isIn(['Male','Femal'])
}
}
import {inject, computedFrom} from 'aurelia-framework';
import {Validation} from 'aurelia-validation';
import {UserFactory} from 'framework/factories/user-factory';
import moment from 'moment';
@inject(Validation, UserFactory)
export class AuthRegister {
constructor(validation, userFactory) {
this.userFactory = userFactory;
this.user = this.userFactory.create();
// Validation added here. Passes the item and validation object
this.userValidation = this.user.validator(this.user, validation);
}
createUser() {
// using promise array here because I will be validating more then one model
let promises = [];
promises.push(this.userValidation.validate());
Promise.all(promises)
.then(() => {
console.log('both valid');
})
.catch(error => {
console.log('something not valid');
console.log(error);
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.