Setting error message in html with knockout validation - knockout-validation

I would like to use knockout-validation by only adding validation rules in HTML5, which works great:
http://jsfiddle.net/gt228dgm/1/
I would then like to change the default error messages generated by the browser (like "This field is required." or "Invalid"). This is pretty easily done in javascript code, But I believe this kind of texts should go into the HTML. Is that possible and how? I guess I'm looking for something like:
<input data-bind='value: firstName, validate: { message: "Please enter first name" }' required pattern="^[A-Za-z]{1,255}$"/></label>

I have implemented a custom knockout binding that solves my issue:
ko.bindingHandlers.validate = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var valueBinding = allBindings().value;
var value = valueAccessor();
if (value) {
valueBinding.extend(value);
}
}
};
The binding then looks like this
<input data-bind='value: firstName, validate: { required: { message: 'Full name is missing' }, pattern: { message: 'Full name should be max. 255 alphanumeric characters' } }' required pattern="^[A-Za-z]{1,255}$"/>
Any other suggestions?

I've been playing these days with knockout validation. For your need, you could use validationMessage binding. Here is an example of your code modified, to use this binding: http://jsfiddle.net/elbecita/gt228dgm/4/
Basically, you'd end up having something like:
<span data-bind="validationMessage: firstName, text: 'Your error.'"></span>
<input data-bind='value: firstName, valueUpdate: "input"' required pattern="^[A-Za-z]{1,255}$" />
I've added the valueUpdate binding just to have the validation message shown immediately. And then, in your javascript code, when you define the validation configuration, be sure to turn to false the insertMessages option. If not, you'll see the default message too.
But... I think is easier and cleaner to do this with the knockout extenders in javascript code, having all custom messages centralized in some sort of constants file, instead of having them scattered through the html.
Anyway, dig into the knockout validation bindings, they may help you with your needs. :)

Proper way to handle custom validation message in KO is to create a custom validation not binding.
Here is an example of simple number validation
ko.validation.rules['integerFormat'] = {
validator: function (value, options) {
if (!value) return true;
var regex = /^\d+$/;
var matches = regex.test(value);
if(matches){
value = parseInt(value,10);
return typeof value== "number" && isFinite(value) && value%1===0;
}else{
return false
}
},
message: app.MyCustomIntegerNotValidMSG
}
app.MyCustomIntegerNotValidMSG is just a variable holding your MSG
You would use this in your ViewModel like this
self.myIntegerToValidate = ko.observable().extend({
integerFormat:{}
});;

Related

Conditionally format value in React-Final-Form based on data in form?

I am displaying a currency value in a react-final-form. I am using a format function on the field.
const formatMoney = (value) => {
if (!value) return value;
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
minimumFractionDigits: 2,
currency: 'USD'
});
return formatter.format(value);
};
The problem is the currency is another option in the form. I do not see a clean way to access the rest of the values inside a format function.
After asking the question, I figured out this work around, pass the values into the render function of the form and pass down to the format function like this:
<Field
name="total"
type="text"
readOnly
component={LabeledInput}
placeholder="10"
label="Total"
help="Estimated total including tax"
format={v => formatMoney(v, values.currency)}
/>

Form Data not submitting complete string

Could someone tell me what my form data's string ends at the comma? I'm sending a form with react with a string with foo, bar but only foo is sent in the form data. This has nothing to do with the database as in the chrome dev tools, under network, I see only one value of the string. Here's a image of my actual views:
Only Wordpress, gets submitted. Noticed the ,?
Some code, in React (I'm using react-select):
<form action="/" method="post">
<Select ref="stateSelect" options={skillsOptions} simpleValue multi={this.state.multi} value={this.state.skillsSelectValue} name="skills" onChange={this.skillsUpdateValue} valueKey="value" labelKey="name" loadOptions={this.getContributors} />
</form>
skillsUpdateValue: function(newValueCnd) {
// var str = newValueCnd.split(',');
this.setState({
skillsSelectValue: newValueCnd
});
this.setState({
skills: newValueCnd
});
},
Am I missing something from the form? Using just Rails, all words great.
Edit:
Input options:
var skillsOptions = [
{ value: 'one', name: 'One' },
{ value: 'two', name: 'Two' }
];

Parsley to validate a file was uploaded?

I am using Parsley throughout an application on text fields and selects. Is there a way to use Parsley to validate a file was uploaded within a file input?
<input type="file" name="letterFile1" class="custom-file-input" data-parsley-required="true"/>
You can always write a custom validator, with Parsley.
window.ParsleyConfig = {
validators: {
filerequired: {
fn: function (value, requirements) {
if (value=="") return false;
else return true;
},
priority: 32
}
}
};

Accessing values in ViewModel in a dxList - PhoneJS

So in my PhoneJS web app, I have a dxList widget, with checkboxes on each item. I want to be able to select multiple items, and then do something with them. I'm trying to bind the 'checked' binding to an observable, but I get an 'undefined' error.
Here's the code for the dxTemplate for the list
<div data-options="dxTemplate:{name:'item'}">
<span data-bind="text: $data.information"></span>
<div data-bind="dxCheckBox: { checked: check_boxes }"></div>
</div>
The problem is that check_boxes is in the viewModel, not the item array. I need to access values in the viewModel. I've tried viewModel.check_boxes, but with no success.
Here's the js code:
AppNamespace.otherView = function (params) {
var viewModel = {
my_list: [
{
key: 'Group 1',
items: [
{ information: 'Test 1' },
{ information: 'Test 2'},
{ information: 'Test 3' }
]
}
],
check_boxes: ko.observable(false),
//...etc
Has anyone had any experience with this, and is there a solution?
Thanks!
Knockout provides special properties to access parent binding contexts. In your case both $parent and $root should work.
More on this topic in Knockout docs: Binding context.

how to use the groovy controller element in JavaScript

I have
def exception = request.exception.stackTraceLines
in Groovy controller. How can I get the value of the exception in the JavaScript.
If you are adding exception to your return like this.
flash.message = message(exception: 'Error: xxx');
you can get it like this
<div class="message" role="status"> ${flash.message} </div>
just use ${ your flash.your_var_name}
You have multiple options to fix this. When using javascript I usually use a wrapper which can hold the error message/stacktrace. It depends on where and how you want to do the error handling. Example:
def book = new Book(params)
book.validate()
render (contentType: "text/json") {[
"data": book,
"errors": book.hasErrors() ? book.errors : null
]}
Then you can check if "errors" has a value when getting back your JSON to determine if there are errors in the input for instance. (Elvis operator probably works too, book.errors ?: null) Other (uncatched) exceptions I handle in the error callback I usually define in my JavaScript. (jQuery mostly, (with malsup jquery.form.js in this case))
$(function() {
$("form").live("submit", function() {
$(this).ajaxSubmit({
error: function (msg) {
/* Catch hard errors here (500's) */
alert("Error occurred: " + msg);
},
success: function(wrapper) {
if (wrapper.errors != null) {
/* Handle model errors here */
} else {
/* Parse data here */
var book = wrapper.data;
}
}
});
return false;
});
You can also do this
render(template:"book",model:[book:theBook, exception:exception])
Or like this (didnt try, don't know if works)
render(template:"book",model:[book:theBook, exception:exception!=null?exception:""])
and then access from the GSP like this
${exception.getMessage()}

Resources