I am facing a problem with my validation
Here is my field with extend property
self.searchText = ko.observable("")
.extend({ pattern: { params: /^[a-zA-Z0-9\åäöÅÄÖ]+$/g, message: "Invalid symbols."} });
Regex is well to not allow special symbols But, in runtime I can enter any symbol
What's wrong in my code?
Assuming the problem you're actually trying to solve is "use knockout to prevent special characters", not "use knockout to tell them that they've used special characters", then you'll want something like this:
var allowedChars = /[a-zA-Z0-9\åäöÅÄÖ]/;
var _noSpecialCharacters = ko.observable("");
self.searchText = ko.computed({
read: function () {
//read underlying observable
return _noSpecialCharacters();
},
write: function (newVal) {
//filter disallowed characters
var filtered = newVal.split("").filter(function (char) {
return allowedChars.test(char)
}).join("")
//write to underlying observable
_noSpecialCharacters(filtered);
}
});
You could also wrap this functionality into a custom knockout extension pretty easily, which would let you use syntax like what you're trying to use in the question.
jsfiddle
Related
I want my knockout validator to have a message that depends on the validation of the input. It seems like a very common use case but I can't find any way of doing it... here's a simplistic example of what I'd like to do
ko.validation.rules.dumb = {
validator: function( value )
{
if (value.startsWith( "s")) return {isValid:true}
return {isValid:false, message: value + " needs to start with an s"}
}
}
some_field.extend({dumb: {}});
This sort of works:
ko.validation.rules.sort_of_works = {
validator: function( value)
{
if (value.startWith("s")) return true;
ko.validation.rules.message = value + needs to start with an s";
return false;
}
}
but it really doesn't - because it only works if you only have one field using that validator :(
I tried accessing "this" in the function, but the this is the this of the validator function - which isn't useful, as it doesn't have a message on it. Also - I've seen people make message a function, so it depends on the input itself - but my validation is expensive (think something like parsing, where you want to say exactly where the error is in the string) - and I don't want to do it once for the validation, and then again for the message.
What I want works perfectly with the async validation callback function - in fact that's sort of what I'm mimicking, the validation actually happens on the server - but unfortunately the rest of the app (not written by me) is not really setup to support IsValidating - so I can't use async.
I think the library is designed to chain multiple validations using extend.
So, instead of having one validator function that checks a ton of cases, you create a set of validators that all do one simple check that corresponds to a single error message:
ko.validation.rules.startsWith = {
validator: (val, param) => val?.startsWith(param),
message: 'The field must start with {0}'
};
ko.validation.rules.endsWith = {
validator: (val, param) => val?.endsWith(param),
message: 'The field must end with {0}'
};
ko.validation.registerExtenders();
const myValue = ko.observable()
.extend({ startsWith: "s" })
.extend({ endsWith: "p" });
ko.applyBindings({ myValue });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.4/knockout.validation.js"></script>
<label>
Input a word that starts with an <code>s</code> and ends with a <code>p</code><br>
<input data-bind="value: myValue">
</label>
How can we pass parameters to the i18n model from within a XML view?
Without parameters
<Label text="{i18n>myKey}"/>
works but how can we pass a parameter in that expression?
The only piece of information I've found so far is http://scn.sap.com/thread/3586754. I really hope that this is not the proper way to do it since this looks more like a (ugly) hack to me.
The trick is to use the formatter jQuery.sap.formatMessage like this
<Label text="{parts:['i18n>myKey', 'someModel>/someProperty'],
formatter: 'jQuery.sap.formatMessage'}"/>
This will take the value /someProperty in the model someModel and just stick it in myKey of your i18n resource bundle.
Edit 2020-05-19:
jQuery.sap.formatMessage is deprecated as of UI5 version 1.58. Please use sap/base/strings/formatMessage. See this answer on usage instructions.
At the moment this is not possible. But you can use this simple workaround, that works for me.
Preparations
First of all we create a general i18n handler in our Component.js. We also create a JSONModel with a simple modification, so that immediatly the requested path is returned.
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/model/json/JSONModel"
], function(UIComponent, JSONModel) {
"use strict";
return UIComponent.extend("your namespace", {
/**
* Add a simple "StringReturnModel" to the components' models
*/
init: function() {
// [...] your other code in the init method
// String Return Model
var stringModel = new JSONModel({});
stringModel.getProperty = function(sPath) {
return sPath;
};
this.setModel(stringModel, "string");
},
/**
* Reads out a string from our text domain.
* The model i18n is defined in your manifest.json
*
* #param param text parameter
* #param arr array for parameters
* #return string
*/
i18n: function(param, arr) {
var oBundle = this.getModel("i18n").getResourceBundle();
return oBundle.getText(param, arr);
},
});
});
Now, a model with the context {string>} exists. To use the i18n function in the XML view, we create a formatter function. This function parses the parts of the binding and returns the localized string.
sap.ui.define([
], function() {
"use strict";
var formatter = {
/**
* First argument must be the property key. The other
* one are the parameters. If there are no parameters, the
* function returns an empty string.
*
* #return string The localized text
*/
i18n: function() {
var args = [].slice.call(arguments);
if (args.length > 1) {
var key = args.shift();
// Get the component and execute the i18n function
return this.getOwnerComponent().i18n(key, args);
}
return "";
}
};
return formatter;
});
How To Use:
Together with the string-model you can use the formatter to pass paramaters to your i18n:
<Text text="{ parts: ['string>yourProperty', 'string/yourFirstParamter', 'anotherModel/yourSecondParamter'], formatter: '.model.formatter.i18n' }" />
You can pass how many paramaters as you want, but be sure that the first "part" is the property key.
What is written at the link is correct for complex formatting case.
But if you want to combine two strings you can just write
<Label text="{i18n>myKey} Whatever"/>
or
<Label text="{i18n>myKey1} {i18n>myKey2}"/>
create file formatter.js
sap.ui.define([
"sap/base/strings/formatMessage"
], function (formatMessage) {
"use strict";
return {
formatMessage: formatMessage
};
});
View
<headerContent>
<m:MessageStrip
text="{
parts: [
'i18n>systemSettingsLastLoginTitle',
'view>/currentUser',
'view>/lastLogin'
],
formatter: '.formatter.formatMessage'
}"
type="Information"
showIcon="true">
</m:MessageStrip>
</headerContent>
Controller
var oBundle = this.getModel("i18n").getResourceBundle();
MessageToast.show(this.formatter.formatMessage(oBundle.getText("systemSettingsLastLoginTitle"), "sInfo1", "sInfo2"));
i18n
systemSettingsLastLoginTitle=You are logged in as: {0}\nLast Login: {1}
As ugly as it may seem, the answer given in the link that you mentioned is the way to go. However it may seem complicated(read ugly), so let's break it down..
Hence, you can use the following for passing a single parameter,
<Label text="{path: 'someParameter', formatter: '.myOwnFormatter'}"/>
Here, the someParameter is a binding of a OData model attribute that has been bound to the whole page/control, as it is obvious that you wouldn't bind a "hardcoded" value in a productive scenario. However it does end with this, as you see there isn't a place for your i18n text. This is taken care in the controller.js
In your controller, add a controller method with the same formatter name,
myOwnFormatter : function(someParameter)
{
/* the 'someParameter' will be received in this function */
var i18n = this.i18nModel; /* However you can access the i18n model here*/
var sCompleteText = someParameter + " " + i18n.getText("myKey")
/* Concatenate the way you need */
}
For passing multiple parameters,
Use,
<Label text="{parts:[{path : 'parameter1'}, {path :'parameter2'}], formatter : '.myOwnFormatter'}" />
And in your controller, receive these parameters,
myOwnFormatter : function(parameter1, parameter2) { } /* and so on.. */
When all this is done, the label's text would be displayed with the parameter and your i18n text.
In principle it is exactly as described in the above mentioned SCN-Link. You need a binding to the key of the resource bundle, and additional bindings to the values which should go into the parameters of the corresponding text. Finally all values found by these bindings must be somehow combined, for which you need to specify a formatter.
It can be a bit shortened, by omitting the path-prefix inside the array of bindings. Using the example from SCN, it also works as follows:
<Text text="{parts: ['i18n>PEC_to',
'promoprocsteps>RetailPromotionSalesFromDate_E',
'promoprocsteps>RetailPromotionSalesToDate_E'}],
formatter: 'retail.promn.promotioncockpit.utils.Formatter.formatDatesString'}"/>
Under the assumption, that you are using {0},{1} etc. as placeholders, a formatting function could look like the following (without any error handling and without special handling of Dates, as may be necessary in the SCN example):
formatTextWithParams : function(textWithPlaceholders, any_placeholders /*Just as marker*/) {
var finalText = textWithPlaceholders;
for (var i = 1; i < arguments.length; i++) {
var argument = arguments[i];
var placeholder = '{' + (i - 1) + '}';
finalText = finalText.replace(placeholder, arguments[i]);
}
return finalText;
},
OK, I'm obviously not understanding how functions are used in javascript. Given the below code snippet, mozilla firefox is telling me that calcUpper is not defined. Basically I want to define a function and use that function later on in the view on different fields. I tried moving the function definition outside of the kendo model, but with no better results. Can someone show me how I can achieve this?
var viewModel = kendo.observable({
calcUpper: function (fieldName) {
var value = this.get(fieldName);
if (value == "")
return "";
else
return parseInt(value) - 1;
},
jobNum: '',
SRCPerif: '',
SRCOnTargetUpper: calcUpper('SRCPerif'),
SRCOnTargetLower: '',
SRCConcernUpper: calcUpper('SRCOnTargetLower'),
//...other fields...
});
I have the following issues with my knockout model validations and not sure how to resolve them. Following is my model first of all, with the validation rules:
var Data = function (data) {
this.Val = data;
}
function ViewModel(item) {
var parse = JSON.parse(item.d);
var self = this;
this.Name = ko.observable(parse.Name);
this.UserType = ko.observable(parse.UserType);
this.ID = ko.observable(parse.ID).extend({ required: { params: true, message: "ID is required" }, decimal: { params: 2, message: "Should be decimal"} });
this.Username = ko.observable(parsed.Username).extend({ required: {
onlyIf: function () {
return self.UserType() > 1;
}
}
});
this.WeeklyData = ko.observableArray([]);
var records = $.map(parse.WeeklyData, function (data) { return new Data(data) });
this.WeeklyData(records);
this.WeeklyData2 = ko.observableArray([]);
var records = $.map(parse.WeeklyData2, function (data) { return new Data(data) });
this.WeeklyData2(records);
}
ko.extenders.numeric = function (target, precision) {
var result = ko.dependentObservable({
read: function () {
return target().toFixed(precision);
},
write: target
});
result.raw = target;
return result;
};
Here are my problems:
1) with the ID() observable, I want to restrict it to two decimal points, so I've created the validation extender 'numeric' but it's not working. Is there anything wrong with how I'm using it and how to correct it?
2) Also, if I want to restrict an observable to whole numbers, how can I do that?
3) when I define a rule with a condition, (i.e. Username()), how do I define a custom message for that? I was able to do it for default rules, but with the conditional rules, it's not working
4) I have two observable arrays WeeklyData1 and WeeklyData2 both of which contains Data() objects. I want to have separate min/max rules for these two, for example, min/max - 1,7 for WeeklyData1 and min/max - 1,150 for WeeklyData2. How can I get it done?
4) Right now my error messages appear right next to the data field, but I want all those to appear in a single validation summary, while displaying '*' against the field. I've been told to use Validation-bindings, but I'm not sure how to use it, can someone please give an example?
It's a lot of questions, I know, but I appreciate if someone could help.
Thanks in advance
Instead of diving in your code i have created a small-small demonstrations for your questions. Ok so here we go,
1) with the ID() observable, I want to restrict it to two decimal points.... and 2) Also, if I want to restrict an observable to whole numbers....
Your 1 and 2 question are pretty similar so i covered both of this in a single fiddle. Check this fiddle.
3) when I define a rule with a condition, (i.e. Username()), how do I define a custom message ....
You can use message property to set custom messages, Check this fiddle.
4) I have two observable arrays WeeklyData1 and WeeklyData2 both of which contains Data() objects
I am not clear which this question, what type of data both of these array contains and for what you want to set min/max rule ( array length or other ). So please clear this, than i will try to help on this.
5) Right now my error messages appear right next to the data field.....
This questions answer i already given in your how to? with knockout js validations question (Check update).
Let me know if it helps!
I queried my database using Breezejs using the following code:
viewModel = {
products = ko.observableArray([])
};
var manager = new entityModel.EntityManager('/api/Products');
manager.executeQuery(query)
.then(function (data) {
viewModel.products.removeAll();
viewModel.products(data.results);
});
However the products rows contain numeric properties like Quantity which are wired to my page using the data-bind property. On saving the model through manager.saveChanges() I get a validation error. This is because KnockoutJS saves the edited numbers as strings.
What's the recommended way to get around this issue?
As of breeze v 0.80.2, this capability is now supported. ( along with the capability to customize type coercion)
One option is to create a CustomBinding.
I use this for decimals:
ko.bindingHandlers.decimal = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).blur(function () {
var value = valueAccessor();
var valor = Globalize.parseFloat($(element).val());
if (ko.isWriteableObservable(value)) {
value(valor);
ko.bindingHandlers.decimal.update(element, valueAccessor);
}
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).val(Globalize.format(value, "n2"));
}
};
It's a good question.
Currently, breeze does not attempt type coercion, but...
We have discussed having Breeze automatically attempt to coerce any values used within a set operation to the datatype of the property being set ( as defined in breeze metadata). This would occur across all binding libraries, (i.e angular, backbone etc) as well as knockout.
Please feel free to add this to the breeze User Voice. We take these submissions very seriously.