We are developing a web application based on JSF (v2.0) framework. We need to have custom validations in our application. We decided to extend the JSF validation framework by implementing the Validator class.
So let us say that we have multiple input fields which needs to be validated. These input fields are First Name, Last Name, Email Address. We need the user to enter information in these fields. And email address field will have two validations - Required and isValidEmailAddress.
We should be able to use the custom Required validation in First Name, Last Name and Email Address fields. But each time I want different error messages to be displayed for each field. For example in case of First Name, I want to display First Nameis required. In case ofLast nameI want to displayLast name is required`.
How can I reuse the same Required validation implementation for multiple fields but with different error message? Is it possible to do that in JSF? Could you please let me know?
First of all, you don't need to write your own validation logic for required input in JSF. It's one of the basic amenities provided by the framework itself.
JSF's validation framework is cleanly abstracted from messages related to validation, so the two don't have to depend on each other. Your options:
Each input component has a validatorMessage attribute that allows you specify the text/string that will be displayed to the user on validation error. For your specific use case, JSF has gone one step further to specify the required and requiredMessage attribute for input components; to enforce required input and show messages specifically for required input validation respectively. What this means in your use case is that you don't need to write custom validation logic for required input.
By principle of better design you can configure all your desired validation/conversion error messages in a resource bundle (example here) and reference the entries in the resource bundle within your jsf view.
Implementing the validator interface requires you implement the validate method with the following signature
public void validate(FacesContext ctxt, UIComponent comp, Object value) throws ValidatorException
comp refers to the component being validated from which you can get it's Class, clientId etc. value will provide the submitted value from the component
Related
I have the following scenario: I am trying to process a form and the model attribute is a bean with String and Long properties. As you all guys know, bean validation offers a lot of annotation to help us determine the validity of the data.
What I am facing is that, for the case of the Long attributes, I can only use #NotNull and another annotation (I dont recall its name) to force the user to enter positive numbers. If the user enters for instance "sdf", the application throws a BIG exception. So what I would like to know is If I can intercept the form processing and validate by my own if the user entered a numeric thing before it explodes (because I cant use #Pattern)... and I cant switch that attribute to String...
Was it clear ?.
Use Spring Custom validation. That is Annotation-based validation and you have the ability to create your own custom validation logic. Spring Custom Validation In this link you can find out more examples and how to use it.
I want to use JSR 303 (Hibernate Validator) in my JSF 2 project. However, I have complicated forms and field-level validation is not sufficient. I need to use many #ScriptAssert annotations at class-level of my model and its child beans.
So I want to validate form models manually (inside bean action method for example). But I could not understand how I can preserve which validation message should be shown at which field (as it works automatically when field-level validation is on and processed by JSF).
Also I'll need to specify for some of class-level annotations that their messages are to be shown at specific fields. I do not see a straight way to manage it...
Could you please provide a link to explanations of these questions (or tell me that I am doing something wrong?). I think I fail in googling it because internet is bloating with keywords JSF and validation, sorry.
The most idiomatic way to do that is to create custom Bean Validation validator for your class.
You need to create validation annotiation that you would put at the class level (not field level) and associated with that class validator class.
See for instance:
http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-usingvalidator.html (Example "Class level constraint")
How can I validate two or more fields in combination?
Validation inside managed bean is also possible, you can throw in your action methods proper validation exception, but usually it is cumbersome, hard to reuse and mixes business logic code with validation.
I have a problem with validating some data types.
There are int, short, DateTime and so on except string.
Suppose i have following property in my view model class
public int? LineNumber { get; set; }
When i input incorrect value i get mvc error "The value 'balblabl' is not valid for LineNumber."
But what if i want just out something like "Value incorrect"? Or what if i want to use other language? I have no idea how to do it(of course i can use string instead of int but it is painfull workaround)
i already tried dataannotationsextensions [DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")] attribute. It is not working. I cannt to use custom validation attribute because of after binder convertation i get null value in all cases with incorrect value. I just cannt to do my own validation. I can to write my own binder but it looks like a joke. Really i think custom validation message is one of must have featerus and i cannt belive asp.net mvc doesnt has a simple way to do it.
I would like to add another, in my opinion, easy way to add and maintain custom error messages.
using the FluentValidation NuGet package.
It hooks up with mvc pretty easy have a look here
You can easily specify numerous rules for your models and display custom error messages that can use a resource file an example:
public class CreateProductCommandValidator : AbstractValidator<CreateProductCommand>
{
public CreateAgendaPointCommandValidator()
{
RuleFor(cmd => cmd.price)
.NotEmpty()
.WithMessage(Translations.CreateProduct_Price)
}
}
}
Documentation: FluentValidationDocumentation
Those errors are automatically added by the default model binder when it cannot parse the input string into its destination type. They are not like data annotations, where you can specify a resource instead of a harcoded string error message.
However you can use your own resource files, see this other question. Once you have created the resource file, you will update the global.asax for the default model binder to use it:
DefaultModelBinder.ResourceClassKey = "MyResources";
After a custom resource file has been set in the property ResourceClassKey of the default model binder, values will be resolved according to the following criteria (as per the MSDN):
If the property is not set, MVC uses the standard MVC resources.
If the property is set to an invalid class key (such as a resource
file that does not exist), MVC throws an exception.
If the property is set and the class key exists but the resource
names in the file do not exist in the application, MVC uses the
standard MVC resources.
If the property is set and the specified resources are available,
MVC uses the resources in the file.
If you need to know the key values for a particular message check this. For the message The value '{0}' is not valid for {1}., you will need to add a value with the key DefaultModelBinder_ValueInvalid
I have a POJO named sport with properties sportID, sportName, number of players. Using annotated validation I wrote my own annotation constraint to check if sportName exists in the database already or not. It works great when trying to add a sportName, however if I try to update players without changing the sportName the validation fails as well.
Is there any way to pass in a parameter in annotated validation? For example I would like to pass in sportID to the sportName contraint check so that I can exclude that ID in the db query.
Or is there a better way of doing this? In my controller should I let Spring validate inputs (with #Valid) and then if there are no errors call a validate function to check for business rules?
A better way would be using Validation Groups. (Spring MVC and JSR-303 Validation Groups)
Then you can have the default validation group without the "not exits validator". And have an extra group with the "not exits validator". This would allow you to trigger the "not exits validator" only when you need it. (Unfortunately it is not direct supported in Spring 3.0, there you have to start the validation "by hand")
An other way would be not to implement the validator like a field validator, but more like a class validator. -- Have a look at the different solutions discussed for cross field validation in this Stack Overflow Question. It will give you an idea how to access the id field.
For example imagine I've a rest service, this service takes two parameters :
phone number
text
The goal is to send the message via a sms gateway.
I've a class Message which has two properties destinationNumber and textMessage.
Before calling the gateway, I want to validate the data received by the rest service.
I've two questions relatives to how to validate the data :
Where should I put the validation rules ? in the model or in the controller
How should I use the sfValidator* classes from Symfony to validate the data (ie. where's the documentation for using sfValidator or where can I find some examples)
Any help would be appreciated.
What you want to do is use the form framework for this.
It handles all the validation for you. You pass the data from your REST request to a new form and call validate.
If you create your model the forms are generated for you, take a look at the base classes to see the default validators.
You can override these validators with your own, take one that is similar to what you are trying to achieve (string validator, email validator) and overload it with your own code.
See: http://www.symfony-project.org/jobeet/1_4/Doctrine/en/10 for more info on the forms.