JSF Validation of whole form with optional fields and a lot of dependencies - forms

Just wanted to ask for the best way to solve my problem:
I got a form with multiple inputs/selects and also buttons to add new objects to the databean behind the form. Now my problem is the validation. E.g.: in one of those selects i chose an option. If this option is selected the user has to add a specific type of an object to the large databean behind the form. That's done by selecting values in two further selects. As soon as those are selected (they are submitted onchange by ajax) the user generates a new object by hitting an "Add" button.
On submit those added object (consisting of two values) must have a specific enum type depending on the first selected value and so on..
Now this all (and a lot more) should be validated and error/info messages should be added to the view.
Now my question: whats the best way to achieve this? The error message has to be at a specific place in the view.
I thought of multiple hidden input fields and using the validate attribute to call validation methods of the underlying bean (cause bean values are needed too). And then rendering an error message right at the position of the hidden field. Is this a good solution? Working with the validator attribute and validating the whole form would lead to error messages in areas where the user hasn't made any input yet, right? I would like to avoid that and just validate the current area. Is that possible by using one bean? Otherwise i would have to use multiple validators with a lot of attributes, or use the beanManager to get my underlying bean?

The JSF validation is done per component, not per form. This is by design (and it has a good purposes). There is a lot of misunderstanding on this point and many teams make the mistake of shoehorning their business logic validation into component validation, just because the word "validation" sounds right to them.
The validation you need is different - it's a business level validation. You don't really validate state of a single component, but rather coherence of the data, which is behind the components. You can still use the message framework to display the errors where you want them.
The clean and "proper" way to do it in JSF will be to:
skip the JSF component validation (because it's designed for different case than yours); you want all the values from the component to be put into your backing beans;
put anywhere you need an error message displayed;
write validation logic in your action method. You can use Bean Validation Framework or write the logic by hand;
if no errors are found, the action method performs an action;
on error, depending on the error, display a message in a proper place (using the component id);
if any error occured, don't perform the action and return from the action method.
The action method should look somewhat like this (this is not a copy-paste example, it's just to give you an idea of the flow):
public void doSomething() {
boolean valid = true;
if (startData.after(expiryDate)) {
FacesContext.getCurrentInstance().addMessage("expiryDate", new FacesMessage("Expiry date should come after creation date"));
valid = false;
}
// other checks
// checks could also make use of BVF validator - but then it's better to switch the BFV validation for the whole form
// (if you don't, then any single field validation will disable error checking for the business validation, which
// will look strange for your users)
if (!valid) {
// if we returned immediately upon detecting an error, we would only display the first one.
return;
}
// do the real stuff
}

Related

Accessing om.next sub-component state

I'm just picking up om.next and have run into a situation where I've got some form inputs realized as components which hold on to local state, e.g. validation state, actual input value, etc--this state is updated and accessed via om.next/update-state! and om.next/get-state. The trouble with this seems to be when I wrap the inputs in a form in a parent component I'm unsure how to get the state held by the input components. Is it better to pass along the parent component as a property of the input component? What about situations where there is no parent component?
It seems to me that there are 2 options for the use case you want to achieve:
pass the parent component as an argument as you said
have an entry in the global app-state that represents the current form being edited, which you can update via transact! irregardless of the component corresponding to the input. This way every component that represents an input knows where in the app-state to update itself (which key in the current form) — probably captured succintly in one mutation function.
1) is probably the easiest to implement given the code you have currently, but I always like to go for 2) because it doesn't deviate from the "single source of truth" opinion that Om Next recommends (and tries to enforce). Form data is in fact business data, which might not be desirable to have scattered in components. Testability is just one advantage that I immediately see from such approach.

Play framework- design suggestion for validation

I need to validate if a certain newly added entity, part of my model has already been added. The addition would happen by taking input from a user.
I believe the standard way to do it is to add constraints in the form along the lines of
.verifying( "Already exists", <code to check if entity already exists> )
This would lead to a globalError is the entity already exists. The error message would be a static "Already exists".
What I'm looking for, though, is to also tell the user what possible matches exist, something the globalError would be incapable of doing.
Should I do what I want to do by not adding the validator and by allowing the binding to succeed? This way, when I do a
myForm.fold{ Entity returned as success => <success code>, erroneousForm => <failure code>}
I can take the success branch and then check there if the entity could be duplicate? If similarities exist then I can redirect the user? I feel like this shouldn't be the controller's job, and this is too much of design logic inside controller, this should technically all lie inside the model itself. And the model should only tell the controller that something is wrong and the 'type of w can first create the new element and then upon finding that potential rongness' and the controller can take appropriate action. It shouldn't have to contain code to determine if there is anything wrong.
Can someone please suggest what should be a good way to do it?

Which one is the correct approach for form validation ? Colander's Schema validation or Deform's form validation?

I have just started using Pyramid for one of my projects and I have a case where in I need to validate a form field input, by taking that form field value and making a web-service call to assert the value's correctness. Like for example there is a field called your bank's CUSTOMER-ID. I need to take that(alone) as input and validate at the server level by making a web-service call (like http://someotherdomain/validate_customer_id/?customer_id=<input_value>)lets say.
I am using Colander for form schema management and Deform for all form validation logic. I am confused about where I need to place my validation logic for the CUSTOMER-ID case. Is it at MySchema().bind(customer_id=<input_value>) (which has a deferred validator that queries the web-service) or something at the form.validate(request.POST.items()) ? If I take the deferred validator's path, then MySchema().bind is raising colander.Invalid error for incorrect CUSTOMER-ID. Thats fine. But that error is not at the form level but at the schema level. So how would I tell the user about this in a sane way ?
I have good experience with Django forms so I was expecting something like clean method. A form error like form['customer_id'].error is what I am expecting at the template level. Is it possible with Pyramid's Deform or with Colander ?
So I think the big problem you're having is understanding the separation of concerns of Colander and Deform. Colander is what people like to call a general schema validation library. Which means we define a schema, where each node has a particular data type and some nodes might be required/optional. Colander is then able to validate that schema, and tell us whether or no the data we passed to colander conforms to that schema. As an example, in my web apps, I am often building apis that accept GET/POST params that need to be validated. So in Pyramid, let's say I have this scenario:
request.POST = {
'post_id': 1,
'author_id': 1,
'unnecessary_attr': 'stuff'
}
I can then validate it like so:
# schema
schema = SchemaNode(Mapping(),
SchemaNode(Integer(), name='post_id'),
SchemaNode(Integer(), name='author_id'))
schema.deserialize(request.POST)
And it will error if it can't conform the data to the specified schema. So you can see, colander can actually be used to validate ANY set of data, whether that comes from POST/GET/JSON data. Deform on the other hand is a form library, and helps you create/validate forms. It uses colander for all of the validation needs and as you can see it pretty much just completely delegates validation to colander. So to answer your question, you would do all of your validation stuff in colander, and deform would mostly handle the rendering of your forms.
To see a vivid pyramid example application and deform in action look at todopyramid as a part of IndyPy Python Web Shootout. A todo application was implemented in pyramid, django, flask and bottle. I studied the pyramid example - it is well written, shows deform schema validation and uses bootstrap to show validation messages.
Find more pyramid tutorials here:

xtext check annotation issue

I'm using the #Check annotation in order to validate my dsl. my dsl is for json.
at first the method was invoked for a specific object and once per change
but it suddenly doesn't work in the same way anymore (and i'm not sure what i've done that effected it)
the method signature is:
#Check
public void validateJson(ObjectValue object) {...}
now its entering this method for each node in the gui although i'm editing only one node
The validator works normally in this case. When Xtext re-parses your model, it cannot always avoid re-creating the EMF model that is validated in the Check expression - in other words, the model is practically re-created every time, thus warranting a full validation.
However, in some cases, it is possible that only a partial re-creation of the model is necessary - in these cases it is possible that not all elements are re-validated (however, I am not sure whether this optimization was included).

Does Core Data automatically validate new values when they are set?

In this question, someone asked how to write a validation method for Core Data. I did that, and it looks cool. But one thing doesn't happen: The validation. I can easily set any "bad" value and this method doesn't get called automatically. What's the concept behind this? Must I always first call the validation method before setting any value? So would I write setter methods which call the appropriate validation method first?
And if yes, what's the point of following a strict convention in how to write the validation method signature? I guess there's also some automatic way of validation, then. How to activate this?
Validation is not "automatic" especially on iOS. On the desktop you will have the UI elements handling the call to validation. On iOS you should be calling validateValue:forKey:error: with the appropriate key and dealing with the error should there be one. The reason for this is the lack of a standard error display on iOS and the overhead of validating all values.
Note this comment in the documentation:
If you do implement custom validation methods, you should typically not invoke them directly. Instead you should call validateValue:forKey:error: with the appropriate key. This ensures that any constraints defined in the managed object model are also applied.