JSFiddle - React, Tailwind, and code Playground
by Salmin Skenderovic
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"></script>
<label for="">Name *</label>
<input type="text" data-bind="event: {'keyup': enterKey}, value: customer.name">
<br>
<label for="">Mobile:</label>
<input type="text" data-bind="event: {'keyup': enterKey}, value: customer.mobile">
<br>
<label for="">Telephone *</label>
<input type="text" data-bind="event: {'keyup': enterKey}, value: customer.telephone">
<br>
<input type="button" data-bind="click: sendCustomer" value="send">
CSS
input {
margin: 15px;
}
JavaScript
Customer = function () {
var self = this;
self.name = ko.observable().extend({
required: true
});
self.mobile = ko.observable();
self.telephone = ko.observable().extend({
number: true,
required: {
required: true,
message: 'You must enter a number!'
}
});
}
vm = function () {
//Init
customer = new Customer();
//Validationsteps
firstValidation = ko.validation.group(customer, {
observable: true
}),
//Methods
sendCustomer = function () {
if (firstValidation().length == 0) {
alert("customer has been sent!");
} else {
firstValidation.showAllMessages();
}
},
enterKey = function (d, e) {
if (e.keyCode == 13) {
alert("enter has been pressed..");
sendCustomer();
}
return true;
},
trim = function (str) {
str = str.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
},
// HERE
(function(){
for (x in customer) {
console.log("subscribing to: customer." + x);
customer[x].subscribe(function(val){
console.log("updating the value: " + val)
this.target(trim(val));
})
}
})();
return {
customer: customer,
sendCustomer: sendCustomer,
firstValidation: firstValidation
}
}();
ko.applyBindings(vm);