Search code examples
javascriptknockout.jsknockout-validation

Trigger validation on click on a button in knockout js


I have a form which use KOJs for calculation, I need to implement kojs validation there so that the user should n't submit a blank field in form..

I already tried various resources but they was not very helpful.

Please can you guys solve this problem. Any help will be appreciated.

Below is my code

function ViewModel() {

                this.fullname = ko.observable().extend({ required: true, minLength: 2, maxLength: 10 });

                this.startDate = ko.observable(new Date());

                this.companyname = ko.observable().extend({ required: true });

                this.loanAmount = ko.observable();

                this.email = ko.observable();

                this.phoneNumber = ko.observable();

                this.sellerName = ko.observable();

                this.propertyAddress = ko.observable();

                this.propertyCity = ko.observable();

                this.mortgagePayoff = ko.observable();

                this.realtorCommission = ko.observable('6');

                this.termitePolicy = ko.observable();

                this.closingCosts = ko.observable();

                this.additionalNote = ko.observable();

                this.PropertyCity = ko.observable();

                this.selectedcounty = ko.observable();

                this.no_documents = ko.observable();
                this.fileInput =  ko.observable();
                this.fileName = ko.observable();




                this.submitForm = function()

                {

                    var data = JSON.stringify(

                        {

                            fullname : this.fullname(), 

                            companyname : this.companyname(),

                            email: this.email(), 

                            phoneNumber: this.phoneNumber(),

                            sellername: this.sellerName(),

                            propertyAddress: this.propertyAddress(),

                            propertycity: this.propertyCity(),

                            county: this.selectedcounty(),

                            contractSalesPrice: this.contractSalesPrice(),

                            selectedPropertyType: this.selectedPropertyType(),

                            loanAmount : this.loanAmount(),

                            wireFee : this.wireFee(),

                            mortgagePayoff: this.mortgagePayoff(),

                            realtorCommission: this.realtorCommission(),

                            revenueStamps: this.revenueStamps(),

                            termitePolicy: this.termitePolicy(),

                            closing_fee : this.closing_fee(),

                            title_service_fee: this.title_service_fee(),

                            titleInsurance: this.titleInsurance(),

                            ownersPremium: this.ownersPremium(),

                            loanPremium: this.loanPremium(),

                            comboPrice: this.comboPrice(),


                            no_documents: this.no_documents(),

                            courierFee: this.courierFee(),

                            homeWarranty: this.HomeWarranty(),

                            priorYear: this.PriorYear(),

                            startDate: this.dateformate(),

                            proRatedTaxes: this.ProRatedTaxes(),
                            insured_closing: this.insured_closing(),
                            RecordingFees: this.RecordingFees(),
                            closingCosts: this.closingCosts(),
                            additionalNote: this.additionalNote(),
                            fileName: this.fileName(),
                            fileInput: this.fileInput()


                        });


                    jQuery.post("../view.php", {json:data}, function(response)

                    {
                        //alert(response);
                    window.location.href = 'http://realtytitle.madeby.ws/result/';
                       // on success callback
                        //this.response(response);

                    })

                } 
            }

            ko.applyBindings(new ViewModel());

Solution

  • First of all, you don't need to generate the data object. Knockout has an excellent function for this: ko.toJSON(). Add at the first line of your ViewModel a variable like this:

    var self = this;
    

    That way you can access the viewModel object from any function. Then, on submitForm just set

    var data = ko.toJS(self);
    

    Regarding validation, a simple but not too elegant solution is to create a function that validates data, like:

        this.isValid = function() {
         return self.fullname().length > 0 && 
                self.email().length > 0 &&
                ... && the validations you want.
        }
    

    This function can be use to validate the object on submitForm. Another way is to use a customHandler that validates each observable, like

    this.email = ko.observable(); 
    this.email.valid = ko.computed() { 
      if (self.email())
        return self.email().length > 0;
      return false;
    }
    

    The same with the rest of the elemts. Then, you just need to validate self.email.valid() on your submitForm function. Plus, this allows you to show if the element is valid or no on the user interface. Finally, there is a knockout validation plugin you can use. As you can see, plenty of possibilities!!!