dfmmalaw
6/26/2017 - 4:22 PM

Validating KO validation rules set on observables

Validating KO validation rules set on observables

// declaring validationDialog outside of main iife
var validationDialog;

// defining the observables and setting validation rules 
var SendNotificationsViaApi = ko.observable();
var StandardApiEndpoint = ko.observable().extend({ maxLength: 128, httpsUrl: true });
var OutboundUsername = ko.observable().extend({ maxLength: 64 });
var OutboundPassword = ko.observable().extend({ maxLength: 64 });
var DateDosSigned = ko.observable().extend({ required: true});

// creating validation check at runtime which returns boolean
 var arePropertiesValid = ko.validatedObservable({
    VendorName: VendorName,
    StandardApiEndpoint: StandardApiEndpoint,
    OutboundUsername: OutboundUsername,
    OutboundPassword: OutboundPassword,
    DateDosSigned: DateDosSigned
});

// check if values pass validation (if yes, create object and make ajax call)
if (arePropertiesValid.isValid()) {
        var vendorObject = {
            VendorId: VendorId(),
            VendorName: VendorName(),
            SendNotificationsViaApi: SendNotificationsViaApi(),
            StandardApiEndpoint: StandardApiEndpoint(),
            OutboundUsername: OutboundUsername(),
            OutboundPassword: OutboundPassword(),
            SendInvite: SendInvite(),
            Seamless: Seamless(),
            DateDosSigned: DateDosSigned(),
            DateTestBegin: TestDetailsProvided(),
            ActiveDate: CompleteDate(),
            InactiveDate: InactiveDate(),
            CertificateRequirements: CertificateRequirements()
        };

        var jsonData = ko.toJSON(vendorObject);

        $.ajax({
            url: "../../ApiVendor/saveVendor",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            cache: false,
            data: jsonData,
            success: handleSubmitSuccess,
            error: handleSubmitError
        });
    } else {
        return false;
    }
}

// defining the validationDialog variable that was declared at top of page
$(document).ready(function () {
    ko.applyBindings(apiVendorIndex);
    validationDialog = st.Util.initAlert('div#validationDialog');
});
<!--this div needs to be added where the error message is going to show-->
<div id="validationDialog" class="alert alert-danger hidden-during-load">
    <button type="button" class="close" data-hide="alert">&times;</button>
    <h4 class="title">Warning</h4>
    <span class="message"></span>
</div>