Problem

Implemented a custom validator for FileUpload component, see code snippets…

FileUploadField fileUpload = new FileUploadField("fileupload",new Model<FileUpload>());
 
fileUpload .add(new AbstractValidator() { 
 
	protected void onValidate(IValidatable validatable) { 
		FileUpload fileUpload = (FileUpload) validatable.getValue();	
		//validate fileUpload
	}
 
    protected String resourceKey() {
	    return "yourErrorKey";
	}
 
});

However, if user didn’t select any file to upload, and click on the submit button, the attached upload validator will be ignored!?

Solution

By default, AbstractValidator (your custom validator) will not validate on null value, see source code :

File : AbstractValidator.java

	 * @see IValidator#validate(IValidatable)
	 */
	public final void validate(IValidatable<T> validatable)
	{
		if (validatable.getValue() != null || validateOnNullValue())
		{
			onValidate(validatable);
		}
	}

To fix it, just override the validateOnNullValue() method like this :

FileUploadField fileUpload = new FileUploadField("fileupload",new Model<FileUpload>());
 
fileUpload .add(new AbstractValidator() { 
 
       public boolean validateOnNullValue(){
	        return true;
	}
 
	protected void onValidate(IValidatable validatable) { 
		FileUpload fileUpload = (FileUpload) validatable.getValue();	
	}
 
    protected String resourceKey() {
	    return "yourErrorKey";
	}
 
});

Now, when no file is selected, and submit button is clicked, validation will be performed.

Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
[ Read More ] You can find more similar articles at Apache Wicket Tutorials