locked
Help Knockout.js - validation for either home phone or mobile phone RRS feed

  • Question

  • User-523978134 posted
    - either home or mobile phone # required if both are empty, display validation message "Home phone or a mobile phone number is required."
    how to write the conditions in knockout

    <div class="form-row">
    <div class="form-group col-md">
    <label asp-for="HomePhoneNumber"></label>
    <input class="form-control" asp-for="HomePhoneNumber" type="text" data-bind="phoneNumberValue: homePhoneNumber" />
    <span asp-validation-for="HomePhoneNumber"></span>

    </div>
    <div class="form-group col-md">
    <label asp-for="MobilePhoneNumber"></label>
    <input class="form-control" asp-for="MobilePhoneNumber" type="text" data-bind="phoneNumberValue: mobilePhoneNumber" />
    <span asp-validation-for="MobilePhoneNumber"></span></div>
    </div>


    self.homePhoneNumber = ko.observable(source.homePhoneNumber);
    self.mobilePhoneNumber = ko.observable(source.mobilePhoneNumber);

    Tuesday, February 5, 2019 7:09 PM

All replies

  • User-893317190 posted

    Hi srt,

    You could use knockout.validation. Its a validation plugin for knockout.js.

    You could refer to the below code.

    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="../Scripts/knockout-3.4.2.js"></script>
        <script src="../Scripts/knockout.validation.min.js"></script>
        <style>
    /*make the error messages red*/ .validationMessage{ color:red } </style> </head> <body> <form> <div> <label for="homePhone">homePhone</label> <input type="text" data-bind="value: homePhone" /> </div> <div> <label for="mobilePhone"> mobilePhone</label> <input type="text" data-bind="value: mobilePhone" /> </div> <input type="button" value="submit" data-bind="click:Register" /> </form> </body> <script> var ViewModel = function () { var self = this;
    // give the mobilePhone field a required validator, error message is please apply your mobilePhone self.mobilePhone = ko.observable().extend({ required: {message:'please apply your mobilePhone'} });
    // give the homePhone field a required validator, error message is please apply your homePhone self.homePhone = ko.observable().extend({ required: { message: 'please apply your homePhone' } });
    // register a function which will show error messages ,when clicking submit input self.Register = function () { self.errors = ko.validation.group(self); if (self.errors().length == 0) { alert('data is valid'); } else { self.errors.showAllMessages(); } } }
    // initialize the viewModel var viewModel = new ViewModel();
    //applyBindings ko.applyBindings(viewModel); </script> </html>

    The result.

    For more information about validation , you could refer to https://github.com/Knockout-Contrib/Knockout-Validation

    Wednesday, February 6, 2019 3:20 AM
  • User-523978134 posted

    Hello Ackerly , 

    I will need to enter only one number. It should check for either home or mobile number . If both are not entered : error ; 

    I have this js - where exactly should i write the home phone and mobile validation? 

    ;

    (function () {
    var model = JSON.parse($('#modelJson').val() || '{}');
    // ko.applyBindings(new CreditApplicationViewModel(model));
    ko.applyBindings(window.vm = new CreditApplicationViewModel(model));

    var dispositions = {
    REJECT: 'Reject',
    ACCEPT: 'Accept',
    MANUAL: 'Manual',
    ERROR: 'Error',
    TIMEOUT: 'Timeout'
    };

    function handleJSendResponse(response, onSuccess) {
    if (!response) return;

    if (response.status === 'success') {
    onSuccess(response);
    } else if (response.status === 'fail') {
    for (var key in response.data) {
    $.notify('error', response.data[key]);
    }
    } else {
    $.notify('error', response.message || 'An error occurred while saving loan.');
    }
    }

    function CreditApplicationViewModel(source) {
    var self = this;
    source = source || {};

    self.loanId = ko.observable(source.loanId);
    self.applicationNumber = ko.observable(source.applicationNumber);

    self.loanDetails = new LoanDetailsViewModel(source.loanDetails, self);
    self.customerInformation = new CustomerInformationViewModel(source.customerInformation, self);
    self.residence = new ResidenceViewModel(source.residenceInformation, self);
    self.employment = new EmploymentViewModel(source.employmentInformation, self);
    self.banking = new BankingViewModel(source.bankingInformation, self);
    self.coBuyer = new CustomerInformationViewModel(source.coBuyer, self);
    self.termsAndConditions = new TermsAndConditionsViewModel(source.termsAndConditions, self);

    self.decision = new LoanDecisionViewModel(source.decision);

    var steps = {
    'loanDetails': self.loanDetails,
    'customerInformation': self.customerInformation,
    'residence': self.residence,
    'employment': self.employment,
    'banking': self.banking,
    'coBuyer': self.coBuyer,
    'termsAndConditions': self.termsAndConditions
    };

    self.nextStep = function (currentModel, nextStepId) {
    currentModel._editMode(false);
    currentModel.toggleVisible(); //TODO: wire up callback in the knockout binding

    if (!steps[nextStepId].showSection()) {
    steps[nextStepId].edit();
    steps[nextStepId].showSection(true);
    $('html, body').animate({
    scrollTop: $('#' + nextStepId).offset().top
    }, 'slow');
    }
    };
    }

    function AddressViewModel(source) {
    var self = this;
    source = source || {};

    self.address1 = ko.observable(source.address1);
    self.address2 = ko.observable(source.address2);
    self.city = ko.observable(source.city);
    self.stateOrProvince = ko.observable(source.stateOrProvince);
    self.zipCode = ko.observable(source.zipCode);
    }

    function LoanDetailsViewModel(source, parent) {
    var self = this;
    source = source || {};

    self._editMode = ko.observable(true);
    self.showSection = ko.observable(true);

    self._hasCalculated = ko.observable(false);
    self._isCalculating = ko.observable(false);
    self._isSubmitting = ko.observable(false);

    self.resetHasCalculated = function () {
    self._hasCalculated(false);
    };

    self.toggleVisible = function () {
    self.showSection(!self.showSection());
    };

    self.id = ko.observable(source.id);

    // --- User Inputs ---

    self.sellingPrice = ko.observable(source.sellingPrice);
    self.sellingPrice.subscribe(self.resetHasCalculated);

    self.salesTax = ko.observable(source.salesTax);
    self.salesTax.subscribe(self.resetHasCalculated);

    self.numberOfPayments = ko.observable(source.numberOfPayments);
    self.numberOfPayments.subscribe(self.numberOfPayments);

    self.consumerState = ko.observable(source.consumerState);
    self.consumerState.subscribe(self.consumerState);

    self.downPayment = ko.observable(source.downPayment);
    self.downPayment.subscribe(self.resetHasCalculated);

    self.tradeInAmount = ko.observable(source.tradeInAmount);
    self.tradeInAmount.subscribe(self.resetHasCalculated);

    self.isDeferred = ko.observable((source.isDeferred || false).toString());
    self.isDeferred.subscribe(self.resetHasCalculated);

    self.isDeferredText = ko.pureComputed(function () {
    return ucfs.util.parseBoolean(self.isDeferred()) ? 'Yes' : 'No';
    });

    self.sameAsCashDays = ko.observable(source.sameAsCashDays || '');
    self.sameAsCashDays.subscribe(self.resetHasCalculated);

    self.sameAsCashDaysText = ko.pureComputed(function () {
    return self.sameAsCashDays() ? self.sameAsCashDays() + ' Days' : 'None';
    });

    self._cashPrice = ko.pureComputed(function () {
    var sellingPrice = numeral(self.sellingPrice()).value();
    var salesTaxFactor = numeral(self.salesTax()).value() || 0;
    var salesTaxAmount = sellingPrice * salesTaxFactor;

    return salesTaxAmount + sellingPrice;
    });

    self._totalDownPayment = ko.pureComputed(function () {
    var downPayment = numeral(self.downPayment());
    var tradeIn = numeral(self.tradeInAmount());
    return downPayment.add(tradeIn.value()).value();
    });
    self.totalDownPayment = ko.pureComputed(function () {
    return numeral(self._totalDownPayment()).format('$0,0.00');
    });

    self._unpaidBalance = ko.pureComputed(function () {
    return self._cashPrice() - self._totalDownPayment();
    });
    self.unpaidBalance = ko.pureComputed(function () {
    return numeral(self._unpaidBalance()).format('$0,0.00');
    });


    // --- End user inputs ---

    // --- AS400 Results ---

    self._apr = ko.observable(source.apr);
    self.apr = ko.pureComputed(function () {
    return numeral(self._apr()).format('0.00 %');
    });

    self._financeCharge = ko.observable(source.financeCharge);
    self.financeCharge = ko.pureComputed(function () {
    return numeral(self._financeCharge()).format('$0,0.00');
    });

    self.floridaDocumentStampTax = ko.observable(source.floridaDocumentStampTax);

    self._amountFinanced = ko.pureComputed(function () {
    return self._unpaidBalance() + numeral(self.floridaDocumentStampTax()).value();
    });
    self.amountFinanced = ko.pureComputed(function () {
    return numeral(self._amountFinanced()).format('$0,0.00');
    });

    self._monthlyPayment = ko.observable(source.paymentAmount);
    self.monthlyPayment = ko.pureComputed(function () {
    return numeral(self._monthlyPayment()).format('$0,0.00');
    });

    self._totalLoanAmount = ko.observable(source.totalLoanAmount);
    self.totalLoanAmount = ko.pureComputed(function () {
    return numeral(self._totalLoanAmount()).format('$0,0.00');
    });

    // --- End AS400 Results ---

    self._setModel = function (data) {
    self.id(data.id);
    self._financeCharge(data.financeCharge);
    self.floridaDocumentStampTax(data.floridaDocumentStampTax);
    self._apr(data.apr);
    self._financeCharge(data.financeCharge);
    self._monthlyPayment(data.paymentAmount);
    self._totalLoanAmount(data.totalLoanAmount);
    };

    self.calculatePayment = function (model, e) {
    var $form = $(e.currentTarget).parents('form');
    if (!$form.valid() || self._isCalculating())
    return false;

    self._isCalculating(true);
    $.post({
    url: '/Loans/Create/ContractTerms',
    data: $form.serialize()
    }).done(function (result) {
    handleJSendResponse(result, function () {
    self._hasCalculated(true);

    parent.loanId(result.data.loanId);
    parent.applicationNumber(result.data.applicationNumber);
    self._setModel(result.data.loanDetails);
    });
    }).fail(function (error) {
    $.notify('error', error || 'An error occurred while calculating loan terms');
    }).always(function () {
    self._isCalculating(false);
    });

    return false;
    };

    self.submit = function (form) {
    var $form = $(form);
    if (!$form.valid() || self._isSubmitting())
    return false;

    self._isSubmitting(true);

    $form.ajaxSubmit().done(function (result) {
    handleJSendResponse(result, function () {
    self._setModel(result.data.loanDetails);
    parent.nextStep(self, 'customerInformation');
    });
    }).fail(function (error) {
    $.notify('error', error || 'An error occurred while saving loan terms');
    }).always(function () {
    self._isSubmitting(false);
    });

    return false;
    };

    self.edit = function () {
    self._editMode(true);
    return false;
    };
    }

    function CustomerInformationViewModel(source, parent) {
    var self = this;
    source = source || {};

    self._editMode = ko.observable(true);
    self.showSection = ko.observable(source.showSection);

    self.toggleVisible = function () {
    self.showSection(!self.showSection());
    };
    self.firstName = ko.observable(source.firstName);
    self.middleInitial = ko.observable(source.middleInitial);
    self.lastName = ko.observable(source.lastName);
    self.suffix = ko.observable(source.suffix);

    self.fullName = ko.pureComputed(function () {
    return [self.firstName(), self.middleInitial(), self.lastName(), self.suffix()]
    .join(' ')
    .replace(/\s{2,}/, ' ')
    .trim();
    });

    self.birthDate = ko.observable(source.birthDate);

    self.socialSecurityNumber = ko.observable(source.socialSecurityNumber);

    self.maskedSocialSecurityNumber = ko.pureComputed(function () {
    return 'XXX-XX-' + (self.socialSecurityNumber() || '').split('-')[2];
    });

    self.emailAddress = ko.observable(source.emailAddress);
    self.confirmEmailAddress = ko.observable(source.confirmEmailAddress);
    self.noEmailAddress = ko.observable(source.noEmailAddress || false);


    //self.homePhoneNumber = ko.observable(source.homePhoneNumber);
    //self.mobilePhoneNumber = ko.observable(source.mobilePhoneNumber);

    self.homePhoneNumber = ko.observable();
    self.mobilePhoneNumber = ko.observable();

    self._isValid = ko.computed(function ()
    {

    var homePhoneNumber = self.homePhoneNumber();
    var mobilePhoneNumber = self.mobilePhoneNumber();
    return homePhoneNumber || mobilePhoneNumber;

    }, this)


    self.address = new AddressViewModel(source.address);

    self._isLegalResident = ko.observable(source.isLegalResident);
    self.isLegalResident = ko.pureComputed(function () {
    return ucfs.util.parseBoolean(self._isLegalResident());
    });

    self._declaredBankruptcy = ko.observable(source.declaredBankruptcy);
    self.declaredBankruptcy = ko.pureComputed(function () {
    return ucfs.util.parseBoolean(self._declaredBankruptcy());
    })


    self.requireBankruptcyInfo = ko.pureComputed(function () {
    return numeral(self.declaredBankruptcy()).value() === 1; // 1 = Yes - Discharged
    });

    self.bankruptcyYear = ko.observable(source.bankruptcyYear);
    self.bankruptcyState = ko.observable(source.bankruptcyState);

    self._isSubmitting = ko.observable(false);

    self.submit = function (form) {
    var $form = $(form);
    if (!$form.valid() || self._isSubmitting())
    return false;

    self._isSubmitting(true);

    $form.ajaxSubmit().done(function (result) {
    handleJSendResponse(result, function () {
    parent.nextStep(self, 'residence');
    });
    }).always(function () {
    self._isSubmitting(false);
    });

    return false;
    };

    self.edit = function () {
    self._editMode(true);
    return false;
    };

    self.verifyResidency = function () {
    var residencyAnswer = self._isLegalResident();
    if (residencyAnswer && !ucfs.util.parseBoolean(residencyAnswer))
    $('#residencyValidation').modal();

    };

    self.verifyBankruptcy = function () {
    if ((self.declaredBankruptcy() || '').toString() === '2') // 2 = Open
    $('#bankruptcyValidation').modal();

    };

    self.toggleEmailWarning = function () {
    if (self.noEmailAddress())
    $('#noEmailWarning').modal();

    return true;
    };
    }

    function ResidenceViewModel(source, parent) {
    var self = this;
    source = source || {};

    self._editMode = ko.observable(true);
    self.showSection = ko.observable(source.showSection);

    self.toggleVisible = function () {
    self.showSection(!self.showSection());
    };

    self._isSubmitting = ko.observable(false);

    self.yearsAtAddress = ko.observable(source.yearsAtAddress);
    self.monthsAtAddress = ko.observable(source.monthsAtAddress);

    self.ownershipType = ko.observable(source.ownershipType);
    self.residenceType = ko.observable(source.residenceType);

    self.rentOrMortgageAmount = ko.observable(source.rentOrMortgageAmount);

    self.hasDifferentMailingAddress = ko.observable(source.hasDifferentMailingAddress);

    self.requirePreviousAddress = ko.pureComputed(function () {
    var yearsAtAddress = self.yearsAtAddress();
    var monthsAtAddress = self.monthsAtAddress();

    if (_.isNil(yearsAtAddress) || yearsAtAddress === '' || _.isNil(monthsAtAddress) || monthsAtAddress === '')
    return false;

    var yearsInMonths = 12 * numeral(yearsAtAddress).value();
    var months = numeral(monthsAtAddress).value();
    var totalMonths = yearsInMonths + months;

    var requiredMonths = 12; // required for one full year

    return totalMonths < requiredMonths;
    });

    self.previousAddress = new AddressViewModel(source.previousAddress);
    self.mailingAddress = new AddressViewModel(source.mailingAddress);

    self.submit = function (form) {
    var $form = $(form);
    if (!$form.valid() || self._isSubmitting())
    return false;

    self._isSubmitting(true);

    $form.ajaxSubmit().done(function (result) {
    handleJSendResponse(result, function () {
    parent.nextStep(self, 'employment');
    self._editMode(false);
    });
    }).always(function () {
    self._isSubmitting(false);
    });
    };

    self.edit = function () {
    self._editMode(true);
    return false;
    };
    }

    function EmploymentViewModel(source, parent) {
    var self = this;
    source = source || {};

    self._editMode = ko.observable(true);
    self.showSection = ko.observable(source.showSection);

    self.toggleVisible = function () {
    self.showSection(!self.showSection());
    };

    self._isSubmitting = ko.observable(false);

    self.incomeSource = ko.observable(source.incomeSource);

    self.employer = ko.observable(source.employer);
    self.title = ko.observable(source.title);
    self.monthlyIncome = ko.observable(source.monthlyIncome);

    self.yearsAtCurrentEmployer = ko.observable(source.yearsAtCurrentEmployer);
    self.monthsAtCurrentEmployer = ko.observable(source.monthsAtCurrentEmployer);

    self.yearsAtPreviousEmployer = ko.observable(source.yearsAtPreviousEmployer);
    self.monthsAtPreviousEmployer = ko.observable(source.monthsAtPreviousEmployer);

    self.secondaryIncomeSource = ko.observable(source.secondaryIncomeSource);

    self.requirePreviousEmployer = ko.pureComputed(function () {
    var yearsAtCurrentEmployer = self.yearsAtCurrentEmployer();
    var monthsAtCurrentEmployer = self.monthsAtCurrentEmployer();

    if (_.isNil(yearsAtCurrentEmployer) || yearsAtCurrentEmployer === '' || _.isNil(monthsAtCurrentEmployer) || monthsAtCurrentEmployer === '')
    return false;

    var yearsInMonths = 12 * numeral(yearsAtCurrentEmployer).value();
    var months = numeral(monthsAtCurrentEmployer).value();
    var totalMonths = yearsInMonths + months;

    var requiredMonths = 36; // required for 3 full years

    return totalMonths < requiredMonths;
    });

    self.submit = function (form) {
    var $form = $(form);
    if (!$form.valid() || self._isSubmitting())
    return false;

    self._isSubmitting(true);

    $form.ajaxSubmit().done(function (result) {
    handleJSendResponse(result, function () {
    parent.nextStep(self, 'banking');
    self._editMode(false);
    });
    }).always(function () {
    self._isSubmitting(false);
    });
    };

    self.edit = function () {
    self._editMode(true);
    return false;
    };
    $('#addInput').click(function () {
    dynamic.inputFields.push({ type: 'newtype', displayName: 'newField' });
    console.log(dynamic.inputFields);
    });
    }

    function BankingViewModel(source, parent) {
    var self = this;
    source = source || {};

    self._editMode = ko.observable(true);
    self.showSection = ko.observable(source.showSection);

    self.toggleVisible = function () {
    self.showSection(!self.showSection());
    };

    self._isSubmitting = ko.observable(false);

    self.hasCheckingAccount = ko.observable(source.hasCheckingAccount);
    self.hasSavingsAccount = ko.observable(source.hasSavingsAccount);
    self.hasDebitOrCreditCard = ko.observable(source.hasDebitOrCreditCard);

    self.preferredPaymentMethod = ko.observable(source.preferredPaymentMethod);

    self.submit = function (form) {
    var $form = $(form);
    if (!$form.valid() || self._isSubmitting())
    return false;

    self._isSubmitting(true);

    $form.ajaxSubmit().done(function (result) {
    handleJSendResponse(result, function () {
    parent.nextStep(self, 'termsAndConditions');
    self._editMode(false);
    });
    }).always(function () {
    self._isSubmitting(false);
    });
    };

    self.edit = function () {
    self._editMode(true);
    return false;
    };
    }

    function TermsAndConditionsViewModel(source, parent) {
    var self = this;
    source = source || {};

    self._editMode = ko.observable(true);
    self.showSection = ko.observable(source.showSection);

    self.toggleVisible = function () {
    self.showSection(!self.showSection());
    };

    self._isSubmitting = ko.observable(false);

    self.applicationTermsAcceptedByInitials = ko.observable(source.applicationTermsAcceptedByInitials);
    self.localDate = moment().format('MM/DD/YYYY'); // TODO: format by locale

    self.submit = function (form) {
    var $form = $(form);
    if (!$form.valid() || self._isSubmitting())
    return false;

    self._isSubmitting(true);

    $('#submitModal').modal();

    $form.ajaxSubmit().done(function (result) {
    handleJSendResponse(result, function () {
    parent.decision.reset(result.data);
    });
    }).always(function () {
    self._isSubmitting(false);
    });
    };

    self.edit = function () {
    self._editMode(true);
    return false;
    };
    }

    function LoanDecisionViewModel(source) {
    var self = this;
    source = source || {};

    self.disposition = ko.observable(source.disposition);
    self.minimumAPR = ko.observable(source.minimumAPR);
    self.bidPercent = ko.observable(source.bidPercent);
    self.discountPercent = ko.observable(source.discountPercent);
    self.description = ko.observable(source.description);

    self.approved = ko.pureComputed(function () {
    return self.disposition() === 'Accept'; //dispositions.ACCEPT;
    });

    self.rejected = ko.pureComputed(function () {
    return self.disposition() === 'Reject'; //dispositions.REJECT;
    });

    self.manual = ko.pureComputed(function () {
    return self.disposition() === 'Manual'; //dispositions.MANUAL;
    });

    self.error = ko.pureComputed(function () {
    return self.disposition() === 'Error' || self.disposition() === 'Timeout'; //dispositions.ERROR || dispositions.TIMEOUT;
    });

    self.reset = function (obj) {
    obj = obj || {};
    self.disposition(obj.disposition);
    self.minimumAPR(obj.minimumAPR);
    self.bidPercent(obj.bidPercent);
    self.discountPercent(obj.discountPercent);
    self.description(obj.description);
    };
    }
    })();

    Wednesday, February 6, 2019 1:38 PM
  • User-893317190 posted

    Hi srt,

    Not sure about your logic, but if your want to validation either home phone or mobile number, you could refer to the code below.

       <form>
    
            <div>
               
                <label for="homePhone">homePhone</label> <input type="text" data-bind="value: homePhone"  />
               
            </div>
            <div>
                <label for="mobilePhone"> mobilePhone</label>  <input type="text" data-bind="value: mobilePhone" />
               
            </div>
    <!-- if is not first time, and homePhone and mobilePhone are all empty , show the message--> <div style="color:red" data-bind="visible: !isFirst() && ! homePhone() && !mobilePhone() ">please enter either your phone number or mobilePhone</div> <input type="button" value="submit" data-bind="click:Register" /> </form> </body> <script> var ViewModel = function () { var self = this; self.mobilePhone = ko.observable() self.homePhone = ko.observable()
    // record whether it is the first submit , if it is, not show the message self.isFirst = ko.observable(true); self.flag = ko.observable(false); self.Register = function () {
    // when submit the form , change the isFirst to false self.isFirst(false); } } var viewModel = new ViewModel(); ko.applyBindings(viewModel); </script>

    The result.

    Best regards,

    Ackerly Xu

    Thursday, February 7, 2019 5:41 AM