Validating with knockout-validation - knockout-validation

Working with knockout.js (and knockout-validation) I have this:
self.nickname = ko.observable("").extend({
required: true,
minLength: 3
});
and
<input type="text" data-bind="value: nickname" class="short" maxlength="30" />
<div class="formRow rowErrorMsg" data-bind="visible: nickname.isValid() == false"><span class="staticImages staticImagesError"></span> <?php text("Enter a valid username") ?></div>
but the problem is that when "nickname" its not valid then apper a text next to the input control. The DIV with the error message start visible and then work fine.
I need to do this:
when "nickname" is not valid then just display the DIV with my custom message and format.
when page is loaded then the DIV have to stay hidden.

You need to configure knockout-validation to not show the error-messages. There are two ways.
The first is via binding:
<div data-bind='validationOptions: { insertMessages: false }'>
<input type="text" data-bind="value: nickname" class="short" maxlength="30" />
<div class="formRow rowErrorMsg" data-bind="visible: nickname.isValid() == false">
</div>
The second one is via code:
Use the ko.validation.init({ insertMessages: false }); function
Use the ko.applyBindingsWithValidation(viewModel, rootNode, { insertMessages: false }); function **contextual
A description of all configuration options can be found at: https://github.com/ericmbarnard/Knockout-Validation/wiki/Configuration
If you have many fields you have to validate you could use an messageTemplate template instead of manually creating all the errorMessage divs.

Related

Knockout-Validation Show Template before input

I have a simple JSFiddle example http://jsfiddle.net/b625zeL5/6/
<script>
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: false,
parseInputAttributes: true,
messageTemplate: 'errorTemplate',
decorateInputElement: true,
errorElementClass: 'error'
}, true);
var ViewModel = function(){
this.email = ko.observable("")
.extend({ required: true })
.extend({ email: true });
this.password = ko.observable("")
.extend({ required: true });
};
var viewModel = new ViewModel();
viewModel.errors = ko.validation.group(viewModel);
ko.applyBindings(viewModel);
</script>
<form>
<span data-bind="validationMessage: email"></span>
<input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
<span data-bind="validationMessage: password"></span>
<input type="text" id="password" data-bind="value: password, validationElement: password, valueUpdate:'keyup'"/>
</form>
<script type="text/html" id="errorTemplate">
Error: <span data-bind="validationMessage: field">X</span>
</script>
As you can see - I disabled insertMessages because I need error messages to show before input field. Thus I added span with "data-bind="validationMessage: email"" before each text input.
I defined in validation config
messageTemplate: 'errorTemplate'
but error messages still plain text. How can I get messageTemplate to work?
Because you turned off insertMessages, knockout validation won't use your error message template and it will use what you inserted above each field.
You have two options:
For each observable that has a validation, add a custom error message.
Example 1:
this.password = ko.observable("")
.extend({ required: {
params: true,
message: "Error: This is required"
}
});
Change your error template to something like this:
Example 2:
<script type="text/html" id="errorTemplate">
Error: <span data-bind="validationMessage: error_field"></span>
</script>
.. and inside the form, you can call the template like:
<form>
<!-- ko template: { name: 'errorTemplate', data: { error_field: email } }-->
<!-- /ko -->
<input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
...
...
see jsfiddle here with example 2 in action : http://jsfiddle.net/mhgv48e8/
Hope it helps :)

Validate on Blur

I've created a JSFiddle to help demonstrate my question: http://jsfiddle.net/jeffreyrswenson/CrYWn/5/
Here's what I'd like to see:
Messages should not appear when page loads.
Messages should appear when submit button is pushed.
Messages should appear after input value is changed and user leaves element. (Tabs or clicks to next field)
Messages should appear after user leave an input without changing.(For example a field is required and the user tabs through the field, but doesn't enter a value. I'd like the validation message to appear when this happens.)
The first four work as I'd expect. Is the last item possible and if so, what do I need to change to enable that behavior?
HTML:
<label>First name:
<input data-bind='value: firstName' />
</label>
<br/>
<label>Last name:
<input data-bind='value: lastName' />
</label>
<br/>
<button type="button" data-bind='click: submit'>Submit</button>
<br/>
<span data-bind='text: errors().length'></span> errors
ViewModel:
var viewModel = function () {
ko.validation.configure({
decorateElement: true,
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
this.firstName = ko.observable().extend({
required: true
});
this.lastName = ko.observable().extend({
required: true,
pattern: {
message: 'Hey this doesnt match my pattern',
params: '^[A-Z0-9]+$'
}
});
this.submit = function () {
if (this.errors().length == 0) {
alert('Thank you.');
} else {
this.errors.showAllMessages();
}
};
this.errors = ko.validation.group(this);
};
You just need to use the standard valueUpdate option of the value binding where you can specify additional events to trigger your property change and with that the validation.
So you just need to add the valueUpdate: "blur" setting on your bindings:
<label>First name:
<input data-bind='value: firstName, valueUpdate: "blur"' />
</label>
<br/>
<label>Last name:
<input data-bind='value: lastName, valueUpdate: "blur"' />
</label>
Demo JSFiddle.
In my case, I needed the value to update after key down because I was making some fields visible if the input had a value. I wanted the underlying value to update but didn't want the validation to show until the user tabbed to the next input.
A bit of CSS and a couple of bindings is what worked for me:
CSS:
div.validationWrapper.standard-focus.has-focus .validationMessage
{
display: none;
}
HTML:
<div class="validationWrapper standard-focus" data-bind="css: { 'has-focus': MyObservableHasFocus() }">
<input class="standard-focus" type="text" data-bind="hasFocus: MyObservableHasFocus, value: MyObservable, valueUpdate: 'afterkeydown'" />
</div>
Knockout:
self.MyObservable = ko.observable('').extend({/* Your validation here */});
self.MyObservableHasFocus = ko.observable(false);
The result is an observable that updates it's value after key up and shows the validation message after it loses focus.

Using uniForm and trying to disable input

I have a form that I have 2 different sets of formfields that are utilized depending on a select box value. The problem I am having is when I try to disable the irrelevant input fields, I the disabled attribute comes up as: disabled="" instead of disabled="disabled" here is the code I am using. It is a fairly complicated form so I will use the relevant fields so I can try to keep it as simple as possible for you all. If you think something is missing... please let me know if you need to see more.
<cfform id="entry-form" ACTION="index-10.cfm?Company" name="send" class="uniForm">
<div class="ctrlHolder"><label for="" style="display:none"><em>*</em>Builder or Individual</label>
<cfselect name="select1" id="select1">
<option value="" <cfif Individual is "">selected="selected"</cfif>>Who is this Case for? (choose one)</option>
<option value="0"<cfif Individual is 1>selected="selected"</cfif>>An Individual Home Owner</option>
<option value="1"<cfif Individual is not 1 and Individual is not "">selected="selected"</cfif>>A Builder</option>
</cfselect>
<p class="formHint">A selection is required</p>
</div>
<!--- this is for individual home owner. --->
<div class="hide" id="hide1">
<div class="ctrlHolder"><label for="" style="display:none"><em>*</em>First name</label>
<cfinput type="text"
name="FirstName"
id="FirstName"
data-default-value="Enter your first name"
size="35"
class="textInput required validateAlpha"
maxlength="50"
value="#FirstName#">
<p class="formHint">First Name is required</p>
</div>
</div>
<div class="hide" id="hide2">
<div class="ctrlHolder"><label for="" style="display:none"><em>*</em>Builder Name</label>
<cfinput type="text" id="builder"
name="BuilderName"
data-default-value="Type a builder's name"
size="35"
class="textInput required"
value="" />
<p class="formHint">Builder's name is required</p>
<cfinput id="builder_hidden" name="BuilderID" type="hidden" value="" />
<cfinput id="builder_hidden_plan" name="PlanID" type="hidden" value="" />
</div>
</div>
</cfform>
<script>
$(document).ready(function(){
$("#select1").change(function(){
if ($(this).val() == "1" ) {
$("#hide2").slideDown("fast"); //Slide Down Effect
$("#hide1").slideUp("fast");
$("#FirstName").prop("disabled", true);
$("#builder").prop("disabled", false);
} else if ($(this).val() == "0" ){
$("#hide1").slideDown("fast"); //Slide Down Effect
$("#hide2").slideUp("fast");
$("#FirstName").prop("disabled", false);
$("#builder").prop("disabled", true);
}
});
</script>
I am using:
jquery-1.9.1.js
jquery-ui-1.10.1.custom.js
uni-form-validation.jquery.js
I found the issue. The disabled property was being added. It was the required class that was keeping this from working. I added removeClass and addClass methods in order to correct this.
Please change the jQuery 'prop' to 'attr' & check the below script once it works fine.....
<script type="text/javascript">
$(document).ready(function(){
$("#select1").change(function(){
if ($(this).val() == "1" ){
$("#hide2").slideDown("fast"); //Slide Down Effect
$("#hide1").slideUp("fast");
$("#firstname").attr("disabled", "disabled");
$("#builder").attr("disabled", false);
}
else if ($(this).val() == "0" ){
$("#hide1").slideDown("fast"); //Slide Down Effect
$("#hide2").slideUp("fast");
$("#firstname").attr("disabled", false);
$("#builder").attr("disabled", "disabled");
}
});
});

jQuery Mobile and Knockout.js templating, styling isnt applied

Ok so this is beginning to drive me insane. I have for several hours now searched and searched, and every single solution doesnt work for me. So yes, this question might be redundant, but i cant for the life of me get solutions to work.
I have a bunch of checkboxes being generated by a jquery template that is databound via knockout.js. However, it turns up unstyled. Afaik, it is something about jquery mobile does the styling before knockout renderes the template, so it ends up unstyled.
I have tried numerous methods to no avail, so i hope someone here can see what i am doing wrong.
(i am using jquery mobile 1.2.0 , jquery 1.8.2 and knockout 2.2.1)
This is the scripts:
<script type="text/javascript">
jQuery.support.cors = true;
var dataFromServer = "";
// create ViewModel with Geography, name, email, frequency and jobtype
var ViewModel = {
email: ko.observable(""),
geographyList: ["Hovedstaden","Sjælland","Fyn + øer","Nordjylland","Midtjylland","Sønderjylland" ],
selectedGeographies: ko.observableArray(dataFromServer.split(",")),
frequencySelection: ko.observable("frequency"),
jobTypes: ["Kontor (administration, sekretær og reception)","Jura","HR, Ledelse, strategi og udvikling","Marketing, kommunikation og PR","Handel og service (butik, service, værtinde og piccoline)","IT","Grafik og design","Lager, chauffør, bud mv.","Økonomi, regnskab og finans","Kundeservice, telefoninterview, salg og telemarketing","Sprog","Øvrige jobtyper"],
selectedJobTypes: ko.observableArray(dataFromServer.split(",")),
workTimes: ["Fulltid","Deltid"],
selectedWorkTimes: ko.observableArray(dataFromServer.split(","))
};
// function for returning checkbox selection as comma separated list
ViewModel.selectedJobTypesDelimited = ko.dependentObservable(function () {
return this.selectedJobTypes().join(",");
}, ViewModel);
var API_URL = "/webapi/api/Subscriptions/";
// function used for parsing json message before sent
function omitKeys(obj, keys) {
var dup = {};
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (keys.indexOf(key) === -1) {
dup[key] = obj[key];
}
}
}
return dup;
}
//Function called for inserting new subscription record
function subscribe() {
if($("#jobmailForm").valid()=== true){
//window.alert("add subscriptiooncalled");
var mySubscription = ko.toJS(ViewModel);
//var json = JSON.stringify(mySubscription);
var jsonSmall = JSON.stringify(omitKeys(mySubscription, ['geographyList','jobTypes','selectedJobTypesDelimited','workTimes']));
//window.alert(jsonSmall);
$.ajax({
url: API_URL,
cache: false,
type: 'POST',
contentType: 'application/json',
data: jsonSmall,
success: function (data) {
window.alert("success");
},
error: function (error) {
window.alert("ERROR STATUS: " + error.status + " STATUS TEXT: " + error.statusText);
}
});
}
}
function initializeViewModel() {
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
}
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
initializeViewModel();
$('#jobmailDiv').trigger('updatelayout');
});
</script>
<script id="geographyTmpl" type="text/html">
<input type="checkbox" data-role="none" data-bind="attr: { value: $data }, attr: { id: $data }, checked: $root.selectedGeographies" />
<label data-bind="attr: { for: $data }"><span data-bind="text: $data"></span></label>
</script>
<script id="jobTypeTmpl" type="text/html">
<label><input type="checkbox" data-role="none" data-bind="attr: { value: $data }, checked: $root.selectedJobTypes" /><span data-bind="text: $data"></span></label>
</script>
Note, "jobmail" is the surrounding "page" div element, not shown here. And this is the markup:
<div data-role="content">
<umbraco:Item field="bodyText" runat="server"></umbraco:Item>
<form id="jobmailForm" runat="server" data-ajax="false">
<div id="jobmailDiv">
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" class="required email" data-bind="'value': email" />
</p>
<fieldset data-role="controlgroup" data-mini="true" data-bind="template: { name: 'geographyTmpl', foreach: geographyList, templateOptions: { selections: selectedGeographies } }">
<input type="checkbox" id="lol" />
<label for="lol">fkfkufk</label>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<p data-bind="template: { name: 'jobTypeTmpl', foreach: jobTypes, templateOptions: { selections: selectedJobTypes } }"></p>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<input type="radio" id="frequency5" name="frequency" value="5" data-bind="checked: frequencySelection" /><label for="frequency5">Højst 5 gange om ugen</label>
<input type="radio" id="frequency3" name="frequency" value="3" data-bind="checked: frequencySelection" /><label for="frequency3">Højst 3 gange om ugen</label>
<input type="radio" id="frequency1" name="frequency" value="1" data-bind="checked: frequencySelection" /><label for="frequency1">Højst 1 gang om ugen</label>
</fieldset>
<p>
<input type="button" value="Tilmeld" class="nice small radius action button" onClick="subscribe();">
</p>
Tilbage
</div>
</form>
Alternate method of invoking the restyling (doesnt work either):
$(document).on('pagebeforeshow', '#jobmail', function(){
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
});
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
$('#jobmail').trigger('pagecreate');
});
Use a custom binding (Knockout) to trigger jQuery Mobile to enhance the dynamically created content produced by Knockout.
Here is a simple custom binding:
ko.bindingHandlers.jqmEnhance = {
update: function (element, valueAccessor) {
// Get jQuery Mobile to enhance elements within this element
$(element).trigger("create");
}
};
Use the custom binding in your HTML like this, where myValue is the part of your view model that changes, triggering the dynamic content to be inserted into the DOM:
<div data-bind="jqmEnhance: myValue">
<span data-bind="text: someProperty"></span>
My Button
<input type="radio" id="my-id" name="my-name" value="1" data-bind="checked: someOtherProperty" /><label for="my-id">My Label</label>
</div>
In my own case, myValue was part of an expression in an if binding, which would trigger content to be added to the DOM.
<!-- ko if: myValue -->
<span data-bind="jqmEnhance: myValue">
<!-- My content with data-bind attributes -->
</span>
<!-- /ko -->
Every dynamically generated jQuery Mobile content must be manually enhanced.
It can be done in few ways, but most common one can be done through the jQuery Mobile function .trigger( .
Example:
Enhance only page content
$('#page-id').trigger('create');
Enhance full page (header + content + footer):
$('#page-id').trigger('pagecreate');
If you want to find more about this topic take a look my other ARTICLE, to be more transparent it is my personal blog. Or find it HERE.

jquery ui tabs functions for each tab

How do you bind a function for each index of the jquery UI tabs?
For example, I am creating a 3 part slide sign up, step 1 is a form and has validation, I want to place the code for that inside the load of step1, while also adding classes to the tabs to disable #2 and #3 when on 1, disable #1 and # 3 when on #2
There is no need to bind a function to the tabs, it's built into the plugin:
From the plugin page:
$('#tabs').tabs({
select: function(event, ui) { ... }
});
Inside the function, you can determine the current tab you are in and do what you need to do from there:
Get the current tab index
currentTabIndex = $('#tabs').tabs('option', 'selected')
Get the current tab content ID (from href) - there might be an easier way, but I haven't found it yet.
currentTabContent = $( $('.ui-tabs-selected').find('a').attr('href') );
but from seeing the other questions you posted about this tab/form system you are trying to use, I threw together a demo here.
HTML
<div id="tabs">
<ul class="nav"> <!-- this part is used to create the tabs for each div using jquery -->
<li class="ui-tabs-selected"><span>One</span></li>
<li><span>Two</span></li>
<li><span>Three</span></li>
</ul>
<div id="part-1">
<form name="myForm" method="post" action="" id="myForm">
<div class="error"></div>
Part 1
<br /><input type="checkbox" /> #1 Check me!
<br />
<br /><input id="submitForm" type="button" disabled="disabled" value="next >>" />
</form>
</div>
<div id="part-2">
<div class="error"></div>
Part 2
<br />Search <input type="text" />
<br />
<br /><input id="donePart2" type="button" value="next >>" />
</div>
<div id="part-3">
<div class="error"></div>
Part 3:
<br />Some other info here
</div>
</div>
Script
$(document).ready(function(){
// enable Next button when form validates
$('#myForm').change(function(){
if (validate()) {
$('#submitForm').attr('disabled','')
} else {
$('#submitForm').attr('disabled','disabled')
}
})
// enable form next button
$('#submitForm').click(function(){
// enable the disabled tab before you can switch to it, switch, then disable the others.
if (validate()) nxtTab(1,2);
})
// enable part2 next button
$('#donePart2').click(function(){
var okForNext = true; // do whatever checks, return true
if (okForNext) nxtTab(2,1);
})
// Enable tabs
$('#tabs').tabs({ disabled: [1,2], 'selected' : 0 });
})
function validate(){
if ($('#myForm').find(':checkbox').is(':checked')) return true;
return false;
}
function nxtTab(n,o){
// n = next tab, o = other disabled tab (this only works for 3 total tabs)
$('#tabs').data('disabled.tabs',[]).tabs( 'select',n ).data('disabled.tabs',[0,o]);
}

Resources