I have a domain property and I want to validate two things;
- URL exists (is reachable)
- URL exists in my local DB.
In order to check these things I created to async validation rules using https://github.com/Knockout-Contrib/Knockout-Validation and applied both of them on my property.
What happens is that each time the response from one of the rules comes earlier and it sets isValidating property to false and I want this property to be true until the response from my second rule came.
Custom rules:
export function enableCustomValidators() { (ko.validation.rules as any)["urlValidationServicePath"] = { async: true, validator: function (url: string, baseUrl: string, callback: any) { getRequest(url, baseUrl, callback, "true"); }, message: 'You must enter a reachable domain.', }, (ko.validation.rules as any)["customerValidationServicePath"] = { async: true, validator: function (url: string, baseUrl: string, callback: any) { getRequest(url, baseUrl, callback, "false"); }, message: "This url already exists in our system. Please contact us at [email protected]", } ko.validation.registerExtenders(); } function getRequest(url: string, baseUrl: string, callback: any, method: string) { var restClient = new RestClient(); restClient.downloadString(baseUrl.concat(url), (responseText) => { method === "true" ? callback(responseText === "true" ? true : false) : callback(responseText === "true" ? false : true); }); }Using of the rules:
export class CompanySetupVM extends BasePageVM { public websiteUrl: KnockoutObservable<string> = ko.observable(undefined); public isValidating: KnockoutObservable<boolean> = ko.observable(false); public constructor() { this.websiteUrl.extend({ required: { params: true, message: CompanySetupVM.ErrorMessageNullWebsiteUrl }, urlValidationServicePath: CompanySetupVM.DomainValidationPath, customerValidationServicePath: CompanySetupVM.CustomerValidationPath }); this.isValidating = ko.computed(() => this.websiteUrl.isValidating(), this); } }In cshtml:
data-bind="text: currentPage().nextButtonText, css: {'button-overlay': currentPage().isValidating(), 'button': !currentPage().isValidating()}, click: nextAction"