Wicket FileUpload validator is not execute?

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.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
0 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors
newest oldest most voted