Is there an easier way than the when
clause when adding conditional validation rules? For example, I would like to do something like this
private setupValidation() {
ValidationRules.off(this.user);
ValidationRules
.ensure((c: IEnterpriseLocationUser) => c.title).maxLength(250).required()
.ensure((c: IEnterpriseLocationUser) => c.contactPhone).minLength(10).maxLength(25).required()
.on(this.user);
if (this.isNewUser) {
ValidationRules
.ensure((c: IEnterpriseLocationUser) => c.emailAddress).required().email()
.ensure((c: IEnterpriseLocationUser) => c.userName).required().maxLength(50)
.ensure((c: IEnterpriseLocationUser) => c.salutationId).required()
.ensure((c: IEnterpriseLocationUser) => c.firstName).required().maxLength(50)
.ensure((c: IEnterpriseLocationUser) => c.lastName).required().maxLength(50)
.on(this.user);
}
Promise.resolve(true)
.then(() => this.vc.validate());
}
However, when I do this, the rules inside the if
block overwrite the “main” rules.
As a side note as to why I am approaching it this way, the when
clause, to me at least, is hard to follow. For example, does the following mean that the email address field is required when it is a new user? Or when it is a new user, it needs to be be an email address with a minimum length of 10?
.ensure((c: IEnterpriseLocationUser) => c.emailAddress).required().when(x => this.isNewUser).email().minLength(10)