How to clear an input field in the Validator class? - jsf-2

In my application, I have the following Validator to validate a captcha input:
#Named(value = "simpleCaptchaValidator")
#RequestScoped
public class SimpleCaptchaValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
Captcha secretCaptcha = (Captcha) session.getAttribute(Captcha.NAME);
// Clear the input field
EditableValueHolder input = (EditableValueHolder) component;
input.resetValue();
// Display an error msg if the entered words are wrong
if (!secretCaptcha.isCorrect(value.toString())) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed!", "You have entered wrong words.");
throw new ValidatorException(msg);
}
}
}
The above Validator works great on non-Ajax requests when users do enter wrong captcha words. However, if users enter the right captcha words but there's a validation failed on other components, the input field for the captcha is not cleared.
I'd be very grateful if you could show me how to solve the above problem.

It doesn't work because the EditableValueHolder#resetValue() is invoked at the wrong moment. You should be invoking it during invoke application phase (at least, after update model values phase), not in middle of validations phase. Namely, when the validate() method returns without exception, then JSF will still set the validated value as component's local value. When the validations phase has failed in general, then the update model values phase won't be invoked and the local value still sticks around in the component.
Based on the information provided so far, it isn't possible to propose the right approach. If this is a custom component, then just don't write the value during encode(). Or, if this is an existing component, then perhaps your best bet is to create a custom converter which stores the submitted value as a custom component attribute and then returns null in getAsObject(). In the validator, you then just grab that custom component attribute as value. As last resort, attach a PhaseListener which resets the component at the right moment.

Related

jquery unobtrusive validation: custom methods do not fire after postback

This is an asp.net framework 4.8 mvc application using jquery unobtrusive validation.
I'm using custom validation methods in the usual fashion.
First, I've added the custom validation attribute in the model:
public class MyValidateAttribute : ValidationAttribute, IClientValidatable
{
private const string errorMessage = "My custom error message.";
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = errorMessage,
ValidationType = "myvalidateattribute"
};
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//server-side validation here
}
}
And then applied the validation attribute to a property in the usual fashion:
[MyValidateAttribute]
public bool MyProperty {get;set;}
In javascript I add a matching custom client-side validation method, which is loaded in the $(document).ready() event:
$.validator.addMethod("myvalidateattribute",
function (value, element, param) {
//client side validation here
return false;
}
return true;
});
$.validator.unobtrusive.adapters.addBool("myvalidateattribute");
This works fine. The custom validation fires when I submit the form, which I do like so on a button click:
let $form = $('form');
//clear the validation summary
$form.validate().resetForm();
$form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul").empty();
//reset unobtrusive field level
$form.find("[data-valmsg-replace]")
.removeClass("field-validation-error")
.addClass("field-validation-valid")
.empty();
if ($form.valid()) {
$form.submit();
}
I've been following this pattern for years and it has worked flawlessly. All of the validation fires client-side, and then fires again server-side. The server-side validation is a failsafe. Any validation problem is caught client-side. Any server-side validation error is assumed to be an attempted hack, and I throw an application exception.
I now have a new requirement where I must do some validation server-side, after the form is posted, and send the form back to the browser in an invalid state if the server-side validation fails. This works, but when I send the model back to the browser none of my custom validation fires.
Here is how the server-side validation looks in the controller method:
public ActionResult MyControllerMethod(MyModel myModel)
{
if (MyServerSideValidationFails(myModel))
{
myModel.MyProperty = false; //this is a validation error
TryValidateModel(myModel);
return View("MyView", myModel);
}
//because of client-side validation any invalid model should be assumed an attempted hack
if (!ModelState.IsValid)
throw new ApplicationException("ModelState should never be invalid.");
//other server-side code here
}
If I now resubmit the form, none of my custom validation fires, and so I get an application exception.
When I step into the $(document).ready event when the model is sent back to the browser, all of my $.validator.addMethod() calls are done successfully. But when I then re-submit, and step into the $form.valid() method in the javascript, I notice that the rules collection for each element does not contain any of my custom validation methods. All of the non-custom validation fires as normal (maxlength, required and etc). Just the custom validation is missed.
It's not just deliberately setting the model invalid on the server that causes the problem. As a workaround, in my controller method, I'm doing a RedirectToAction to the GET method that initially loads the page. Since I don't want the user to lose all of the information in the model, I tried creating a new model, setting all of the properties on that model from the posted model, then storing the new model in TempData. When I'm redirected to the GET action I pulled the model out of TempData and displayed the page using it. I still get the same problem--none of my client-side custom validation fires on re-submission.
It appears that posting the model back, and then loading the page with a model, breaks my client-side custom validation. What am I missing?

How to make business validations on fields in editable Table?

Here is the deal: I have a Table who uses a BeanItemContainer of "MyBean". "MyBean" is not really relevant, it contains only 1 String and 2 Date objects.
But the user must be allowed to change theses values for each instance of MyBean in my container.
To do that, it's easy, just do myTable.setEditable(true). Or a little bit more complex, create a Table.ColumnGenerator who returns a Field (add a ValueChangeListener to push the new value inside the bean).
With the Table.ColumnGenerator, I'm also able to add specific validations for each Field, that's great!
The purpose of this is to render the Field in "error mode".
But there is something I'm not able to do: make my business validations after the user clicks on the "Save" button and retrieve the corresponding field to call the method setComponentError(...).
Only basic validations can be done (integer only, max value, date time range, ...) but for more complex validations (business requirements) I don't know...
How can I do that?
You can write your own custom validators by implementing Validator interface and in them implement custom business logic.
public class MyValidator implements Validator {
void validate(Object valueToValidate) throws Validator.InvalidValueException {
//Your Business logic
}
}

jsf2 highlight components with FacesMessages (o:highlight)

i have some input components that should be validated only when a specific action is executed under all other circumstances they should accept every input.
This way i can't use a normal validator but have a commandButton that evaluates the data in it's action Method and creates some FacesMessages related to specific clientIds if something is missing.
Now i normaly use the OmniFaces o:highlight component to point to fields that require further action but in this case the input-components are valid and thus the highlight component does not take them into account.
Now i wonder if it would be possible to have this behavior depended on the List of Ids with Messages.
Something like this:
for (Iterator<String> it = FacesContext.getCurrentInstance()
.getClientIdsWithMessages(); it.hasNext();) {
String clientId = it.next();
List<FacesMessage> messageList = FacesContext
.getCurrentInstance().getMessageList(clientId);
if (messageList != null) {
for (FacesMessage msg : messageList) {
... // build json with clientIds (maybe check for UIInput
}
}
}
If needed this way one could possibly introduce new Style classes for info, warn and error messages. Maybe it's even a bit faster cause not the whole component tree has to be visited, but that s just a guess.
So what s your opinion? This is a rather hard change on the current behavior so i m not sure if this guess will make it into omnifaces or must be implemented individualy.
Now i wonder if it would be possible to have this behavior depended on the List of Ids with Messages.
From the javadoc of the very same method as you linked there:
Note that the FacesContext#getClientIdsWithMessages() could also be consulted, but it does not indicate whether the components associated with those client IDs are actually UIInput components which are not UIInput#isValid().
So, you would for every single client ID still need to use UIViewRoot#findComponent() in order to find the component, figure its type and verify the validity. This is much more expensive than a single tree visit.
If you really need to perform validation in action method, your best bet is to mark the context and inputs as invalid yourself.
FacesContext context = FacesContext.getCurrentInstance();
context.validationFailed();
((UIInput) context.getViewRoot().findComponent(clientId)).setValid(false);
Alternatively, to satisfy the concrete functional requirement,
i have some input components that should be validated only when a specific action is executed under all other circumstances they should accept every input.
just use a normal validator wherein you check the invoked action:
public void validate(FacesContext context, UIComponent component, Object value) {
if (!context.getExternalContext().getRequestParameterMap().containsKey("formId:buttonId")) {
return;
}
// ...
}
I.e. when <h:form id="formId"><h:commandButton id="buttonId"> is invoked, then validation will be performed. That's always better than performing validation at the wrong place.

JSF2 converted and required on same input

I'm having an issue with converters and validators.
I have an input text which takes a CSV list. I have a converter that turns it into a list of String. This all works fine. Although I want to make the field required. But with the converter it seems to ignore any validator I attach as well as the required attribute on the input.
I attempted to solve this by throwing a converter Exception if the value is blank. This almost works, although it gets more complicated since I have a radio group just above that on the form with immediate=true. Immediate skips the validator just fine although seems to still attempt the converter. The next best thing I can think of is to validate in my action and add the faces message manually but I'd rather avoid that since I'll have to hard code the client ID into a Java class.
Any idea how to do this properly?
The converter is invoked before the validators.
Inside the converter, you just need to return null when the submitted value is null or an empty string.
#Override
public String getAsObject(FacesContext context, UIComponent component, Object value) {
if (value == null || ((String) value).isEmpty()) {
return null;
}
// ...
}
You should not throw a converter exception when the value is null or empty. This way the validators won't be fired. The converter should after all not validate the value, it should only convert the value.

ASP.NET MVC: Is Data Annotation Validation Enough?

I'm using the Data Annotation validation extensively in ASP.NET MVC 2. This new feature has been a huge time saver, as I'm now able to define both client-side validation and server-side validation in one place. However, while I was doing some detailed testing, I realized that it's quite easy for someone to bypass the server-side validation if I relied on Data Annotation validation alone. For example, if I defined a required field by annotating the property with the [Required] attribute and placed a textbox for that required field in a form, a user could simply remove the textbox from the DOM (which can easily be done through Firebug) and now the Data Annotation validation will not be triggered on that property during ModelBinding inside of a Controller. To ensure that the "required" validation is triggered, I can repeat the validation after ModelBinding happens, but then I'd be repeating my validation logic.
What is everyone's recommendation on validation? Is Data Annotation validation enough? Or does the validation need to be repeated to ensure that validations get triggered in all situations?
Follow-up comment:
Based on the answers below, it seems that I can't rely on the Model Binder and Data Annotation validation alone. Since we're concluding that additional server-side validation is required, is there an easy way for my Service layer to trigger validation based on what's been defined in the Data Annotations? It seems that this will get us the best of both words...we won't need to repeat the validation code, but we'll still ensure that the validation gets executed even if Model Binder doesn't trigger it.
I'm going to post this follow-up comment as a separate question, as it poses a different question than the original one.
I think to be vigilant concerning security you should choose to you make server validation the priority and ensure that this is always your fallback. Your server validation should work without the client validation. Client validation is more for UX and tho that is paramount to your design, it is secondary to security. With this in mind you will find yourself repeating your validation. A goal is often trying to design your app so that the server and client validation can be integrated as much as possible to reduce the work required to validate on the server and the client. But be assured you must do both.
If bypassing the client validation (by means of DOM manipulation) is avoiding the server validation (which it seems you are indicating) then your server validation for this instance may not be employed appropriately. You should be invoking your server validation again in your controller action or in a service layer. The scenario you describe should not be defeating your server validation.
With the scenario you describe, the DataAnnotation attributes method should be sufficient. It seems that you simply need to make a few code changes to ensure that your server validation is invoked also when submitting the form.
I paired xVal with DataAnnotations and have written my own Action filter that checks any Entity type parameters for validation purposes. So if some field is missing in the postback, this validator will fill ModelState dictionary hence having model invalid.
Prerequisites:
my entity/model objects all implement IObjectValidator interface which declares Validate() method.
my attribute class is called ValidateBusinessObjectAttribute
xVal validation library
Action filter code:
public void OnActionExecuting(ActionExecutingContext filterContext)
{
IEnumerable<KeyValuePair<string, object>> parameters = filterContext.ActionParameters.Where<KeyValuePair<string, object>>(p => p.Value.GetType().Equals(this.ObjectType ?? p.Value.GetType()) && p.Value is IObjectValidator);
foreach (KeyValuePair<string, object> param in parameters)
{
object value;
if ((value = param.Value) != null)
{
IEnumerable<ErrorInfo> errors = ((IObjectValidator)value).Validate();
if (errors.Any())
{
new RulesException(errors).AddModelStateErrors(filterContext.Controller.ViewData.ModelState, param.Key);
}
}
}
}
My controller action is defined like this then:
[ValidateBusinessObject]
public ActionResult Register(User user, Company company, RegistrationData registrationData)
{
if (!this.ModelState.IsValid)
{
return View();
}
...
}
The DataAnnotation is certainly not enough. I use it extensively also to pre-validate my calls to the domain model to get better error reporting and fail as early as possible.
You can however tweak the DataAnnotation Model yourself to ensure properties with [Required] MUST be posted. (will follow up with code later today).
UPDATE
Get the source for DataAnnotations Model Binder and find this line in DataAnnotationsModelBinder.cs
// Only bind properties that are part of the request
if (bindingContext.ValueProvider.DoesAnyKeyHavePrefix(fullPropertyKey)) {
Change it to
// Only bind properties that are part of the request
bool contextHasKey = bindingContext.ValueProvider.DoesAnyKeyHavePrefix(fullPropertyKey);
bool isRequired = GetValidationAttributes(propertyDescriptor).OfType<RequiredAttribute>().Count() > 0;
if (contextHasKey || (!contextHasKey && isRequired)) {
I wrote my own ValidationService for MVC 1.0 by copying patterns from both xVal's DataAnnotationsRuleProvider and Microsoft's DataAnnotationsModelBinder (and Martijn's comments). The service interface is below:
public interface IValidationService
{
void Validate(object instance);
IEnumerable<ErrorInfo> GetErrors(object instance);
}
public abstract class BaseValidationService : IValidationService
{
public void Validate(object instance)
{
var errors = GetErrors(instance);
if (errors.Any())
throw new RulesException(errors);
}
public abstract IEnumerable<ErrorInfo> GetErrors(object instance);
}
The service is a validation runner that walks the property tree of the object instance it receives and actually executes the validation attributes that it finds on each property, building a list of ErrorInfo objects when attributes are not valid. (I'd post the whole source but it was written for a client and I don't know yet if I'm authorized to do so.)
You can then have your controllers, business logic services explicitly invoke validation when you are ready, rather than relying exclusively on the model binder for validation.
There are a couple of other pitfalls that you should be aware of:
The default DataTypeAttribute in data
annotations doesn't actually do any
data type validation, so you'll need
to write a new attribute that
actually uses xVal regular
expressions (or something else) to
perform server-side data type
validation.
xVal doesn't walk
properties to create client-side
validation, so you may want to make
some changes there to get more robust
client-side validation.
If I am allowed and have time, I will try to make more source available...
See codeProject Server-side Input Validation using Data Annotations
Input validation can be done automatically on the client side in
ASP.NET MVC or explicitly validating the model against the rules. This
tip will describe how it can be done manually on the server-side of an
ASP.NET applications or within the repository code of WPF
applications.
// Use the ValidationContext to validate the Product model against the product data annotations
// before saving it to the database
var validationContext = new ValidationContext(productViewModel, serviceProvider: null, items:null);
var validationResults = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(productViewModel, validationContext,validationResults, true);

Resources