Required error versus validation errors

It seems that Fields in a Form that are required get a red asterisk. This asterisk is present and red even if data is there. If I blank out the field, there’s no different/additional indicator on the field that anything is wrong. The same red asterisk appears whether the required field is blank or has data, so it’s not helpful to distinguish this error.

At the same time, if a Field fails its validator check, a red triangle with an exclamation point is shown, making it clear this field is in error.

Is there a reason why the required field check can’t also show the same red triangle? Or perhaps the red asterisk needs to be removed if the required field has content so it doesn’t look like the same “error” whether the field is empty or not.

Ideas?

If I recall correctly, (which might not be the case) also the required fields get an additional css class assigned to them when they are empty. You could add css styling to it to make the error visible. I like switching the field’s background to light red when it doesn’t pass validation. Also remember to use setRequiredError(String).

The red asterisk for indicating that a field is required is quite standard on the web, and I wouldn’t like it to dissapear/appear depending on the data.

Thanks, Jens. Yes, the v-textfield-error css class is set when it it’s empty, and that’s fine. I, too, have used background color to help make them stand out:

.v-textfield-error { background-color: pink !important; }
.v-select-error { background-color: pink !important; }

I think the asterisk is fine. It’s more like why the required validation doesn’t show the same error indicator (triangle with !) like the field when it fails my validators. That is, if the field is not valid, it should be obvious by looking at the form.

The red asterisk is there whether data is present or not. So it’s not an indicator of error, just being required. And it doesn’t stand out like the other fields in error that have the triangle icon, so people tend to fix those, then get another error because of the missing required, and we’ve found that people stare a while before they realize what’s wrong.

With our background color change, this is made obvious for those who have color vision, but if it had the same triangle icon on its error as when it fails validation (required is just a simple built-in validator for length > 0), it would be clear to all.

First of all let me congratulate the Vaadin team for such an outstanding framework. I have been trying various UI frameworks for a project for almost 6 months and Vaadin looks very promising so far. I am into my second week of prototyping and it has been a very smooth sailing so far. Thank you for the amazing work.

Now, about the required fields: I too second David’s opinion. The red asterisk indicates that the field is required and it shows up all the time. That’s perfectly OK. But, the validation for required fields seem to work different from other validators that I have.

  1. The validation for required fields should kick in only after the form is submitted. Right now, the tool tips with the error message are visible when the form is first rendered. That is not very user friendly.
  2. The error indicator next to the field caption should appear when user submits the form and a required field is empty. It will be confusing for users otherwise.
  3. This is slightly off-topic. Looking at the code, setRequired() does not actually add a validator. So the processing is a bit different from the normal validator flow. First, any other validator I have added does not get invoked till the “required” validation is satisfied. That may or may not be ok depending on scenarios, but I kind of understand the thinking behind it. What is probably required is a way to combine multiple validators to form a composite validator. For example, a ZIP code field should be non-empty and 5 or 9 digits. It would be great if there is a way to combine validators like this: (RequiredValidator AND (Regexpvalidator-5 digits OR Regexpvalidator-5 digits)). This will also provide boolean evaluation short-circuits and will be extremely flexible.

Yes. The red asterisk merely indicates that the field is required. This is standard UI practice that it is always visible and it is actually the entire purpose of the required setting. If you do not want to have the indicator visible always, use a regular validator.

Validation is done immediately (and the component error indicator shows) only if the fields are in the immediate mode. If not in immediate mode, they are validated after commit() is called.

That’s already there, [tt]
com.vaadin.data.validator.CompositeValidator
[/tt]. It’s not mentioned in the Book though.

The logic of the required property may be worth some debate. If you have some enhancements in mind, please file a ticket.

Hey, CompositeValidator is an interesting mention. I had not noted it before. Most of us probably only know what the tutorials, book or sampler show.

As for the US postal code, consider that regex should allow you do check both fields using something like:

^\d{5}(-\d{4})?$

5 digits, and a single option to append a hyphen and 4 digits.

(Remember in Java the backslash has to be doubled in your regex String: “^\d{5}(-\d{4})?$”)

This is what I would expect with setRequired(true).

  1. The red asterisk is always visible
  2. If the user submits the form without a value, the component error indicator will become visible. If an error message is set using setRequiredError() method, that message will show up as a tooltip.

This is for a required field, not validators. I have a field setup with the code below and the tooltip with message “Value is required” shows up when the window is first rendered. It would be more intuitive if the tooltip appears only after user submits the form.


		TextField emailAddressField = new TextField("Email address");
		emailAddressField.setRequired(true);
		emailAddressField.setImmediate(false);
		emailAddressField.setNullRepresentation("");
		emailAddressField.setRequiredError("Value is required");

Wonderful! This is exactly what I was looking for. Thank you!

I’ll do that. Thank you.

Yes, I am using the RegExp validator for this, but I have some scenarios where composite validator will be very handy.

It looks like I remembered how the required fields work a bit wrong earlier. It doesn’t seem to be possible to have the component error indicator visible for an empty field in any way, even with a validator, as the required check blocks the other validators, as you commented earlier.

The required field logic is a bit difficult, because they have to work in several different use cases and they should give the developer some freedom as well.

[list]

[]
Field components can be used inside and outside a form - the required mode and its validation is independent of the form
[
]
Required property should be mostly equivalent with a regular validator
[]
Form can be initially empty (new item) or prefilled with existing values (edit item)
[
]
Errors should not show in initial form for a new item - default setValidationVisible(false) in form makes this possible
[]
If an indicated error is fixed, it should optionally be possible to clear the error indicator immediately - setImmediate(true) for the fields does this automatically
[
]
There’s really no such concept as visited or changed field in Vaadin (only when the data value changes)
[*]
The form error indicator is enough for indicating an empty required field, but it would be nice that it is possible to have the component error indicator visible as well.

[/list]And possibly some other requirements and restrictions as well. Some of the logic for empty required fields was defined in
#1867
and
#2038
.

Enabling the component error indicator for empty required fields has a lot of problems with the other requirements.

One solution is that the required property should be just a visual guide with no relevance to the validity, which should be handled purely with validators. This was actually how it worked in early versions of IT Mill Toolkit 5, the behavior was changed in
#1708
. But committing empty required fields if the programmer has forgotten to add the validator could become a common source of crashes. There may have been some other reasons as well.

Forms are revised in Vaadin 7 at some point this year, so the required attribute could be rethought.

Well yes, the fields are validated when they are shown first, and after their value is changed and sent to server (for example after button click).

You can disable the tooltip with setValidationVisible(false) for the fields (not the form). After submitting the form, you’ll have to enable the setting for every field if you want to show the tooltips. The form’s setting is enabled automatically, but not for the fields.

Has anyone figured out how to show the error icon when a field is empty? I set both setRequired and setRequiredError and all i get is a message when i hover over the field, no indicator is show to the left

Thanks
Jeff

I have a problem with this as well - and I can’t say I agree with the reasoning for why “required” is handled differently from other validators.

Marko wrote:

Quite frankly, if a developer simply forgets to add a validator - ANY validator, you’re going to have problems. This is true whether the validation is around the property being required; or a proper email address; or some sort of reg-exp validation.

As it stands; the current implementation precludes certain use cases from being implemented: for instance; imagine if a Form (or Table) is to show information from some source that cannot itself be validated. Putting validation markers on empty required fields then becomes a necessary requirement.

One specific use case I have is this: in my applications; admins can upload users from an excel sheet. After the upload and parse is complete; the users which will be created are displayed in a “preview” mode in a table. At that point; the admin can go and edit the data:

Upload dialog:

Upload & parse progress

Preview result:

As you can see from the third image; I’m simulating some problems in the uploaded data. The first user (Harry Walsh) has an invalid email address. The validator warning shows on this field so that’s fine.

However, the 4th user( Jeff Caveroff) has no account. Account is a required field. I’ve actually attached a custom Required Validator to that field:


public class RequiredValidator extends AbstractValidator {

	public RequiredValidator(String errorMessage) {
		super(errorMessage);
	}

	public boolean isValid(Object value) {
		System.out.println("Validating " + value);
		if(value == null)
		{
			return false;
		}
		else
		{
			if(value instanceof String)
			{
				if(((String) value).length()==0)
				{
					return false;
				}
			}
			
			return true;
		}
	}

}

However, with the current implementation; the table (or form) does not call validators on any field that is null; so my validator is never called and the field has no v-textfield-error style that I could possibly style.

I would rather see the behavior changed so that the concept of “required” is just another validator. The fear that developers may forget to add a validator to required fields could easily be addressed by doing something like this in the DefaultFieldFactory:


if(field!= null && field.isRequired())
			{
				field.addValidator(new RequiredValidator(field.getCaption()+ " is required."));
			}

For what it’s worth; I have a workaround.

In the form; you can override this method:


/**
     * Adds a new property to form and create corresponding field.
     * 
     * @see com.vaadin.data.Item#addItemProperty(Object, Property)
     */
    public boolean addItemProperty(Object id, Property property) {

        // Checks inputs
        if (id == null || property == null) {
            throw new NullPointerException("Id and property must be non-null");
        }

        // Checks that the property id is not reserved
        if (propertyIds.contains(id)) {
            return false;
        }

        propertyIds.add(id);
        ownProperties.put(id, property);

        // Gets suitable field
        final Field field = fieldFactory.createField(this, id, this);
        if (field == null) {
            return false;
        }

        // Configures the field
        field.setPropertyDataSource(property);

        [b]
if(field.isRequired() && property.getValue()==null)
        {
                  field.addStyleName("required-field-not-set");

        }
[/b]

        // Register and attach the created field
        addField(id, field);

        return true;
    }

In the table, you can override this method:


protected Object getPropertyValue(Object rowId, Object colId,
            Property property) {
        if (isEditable() && fieldFactory != null) {
            final Field f = fieldFactory.createField(getContainerDataSource(),
                    rowId, colId, this);
            if (f != null) {
                f.setPropertyDataSource(property);

              [b]
  if(f.isRequired())
	            		{
	            			if(property.getValue()== null)
	            			{
	            				f.addStyleName("required-field-not-set");
	            			}
	            		}
[/b]

                return f;
            }
        }

        return formatPropertyValue(rowId, colId, property);
    }

Bolded is what I added. You can then define .required-field-not-set as a style in your styles.css sheet and so attach the icon to the field.

One last comment on my workaround: this still doesn’t call validators; it just adds an extra style to required fields if the property is null; so if you want the hover-over hint to appear; you will need to setRequiredError(message) on the field; i.e.:

For a css style; I’m using:



.required-field-not-set{
background-image: url('../tpn/img/general/error-indicator.png') !important;
	background-repeat: no-repeat !important;
	background-position: right 50% !important;
	background-attachment: scroll !important;

}

And the result looks like this:

Could you please let me know the CSS that I should use to switch the color of field’s background whenever it fail the validation?
I have tried
.v-textfield-error { background-color: pink !important; }
But the problem is that field’s background has switch its color initially. N that’s what I don’t want. I only want it to switch only after submit and when it fails the validation.
thank in advance.

Hello,

I encounter the same problem.

What are we supposed to do to have the exclamation mark appear ? Isn’t that supposed to work automatically ?

Thank you.

Nicolas

When someone submits the form, and on certain events (eg textChange), you can do something like this:


	private void doBlankFieldValidation()
	{
		myComboBox.setComponentError(null); // clear any previous error messages
		if (isFieldBlank(myComboBox))
		{
			myComboBox.setComponentError(new UserError("Blank values not allowed."));
		}
	}

	private boolean isFieldBlank(AbstractField field)
	{
		boolean isBlank = field == null 
			|| field.getValue() == null 
			|| StringUtils.isBlank(field.getValue().toString());
		return isBlank;
	}

Where do you have the field? Which Vaadin version.

The fields need to be immediate so that their values are communicated to the server as soon as you make changes (and move focus out of the field or press enter).

The required indicator is shown (as a part of the field caption) by the layout containing the field. If you e.g. use a TextField directly in a Table cell, no caption is rendered and thus no required indicator either.

If using the error style as mentioned earlier in the thread is not good for you, one way to get it showing would be to wrap the field in a CustomField (class FieldWrapper from the CustomField add-on for Vaadin 6, or integrated in Vaadin 7) with the field shown e.g. in a CssLayout.

I don’t do the validation by hand, I use Vaadin’s validation mechanisms.

Anyway,
myField.setComponentError(new UserError(“Blank values not allowed.”))
generates only the tooltip under the mouse on the field. But no exclamation mark on the field. And no exclamation mark on the Form. The validation is working, committing is blocked, but visually
it is not very user-friendly
. :-/

Nicolas

Hello Henri, thank you for taking interest in this problem.

I use Vaadin 6.8.0.

I have all my fields in a Form. The Vaadin docs are not very clear about
setImmediate
, but now I have set this to
true
, and all this has changed is the update of the error indicators on focus change, which is a good thing. However, the “error indicators” on the fields are only the tooltips who need the mouse to show. Having the red "
!
" would be better.

The docs of Vaadin describe the approach as much more straightforward than the complicated workarounds you are suggesting.

Nicolas B.

There still no solution to have the ! mark appear on empty required fields?
I also don’t think this is user friendly.

The only think I came up with is to not use the setRequired field and set the * in the Caption and add my on Validator.
But then I don’t have a different colour for the * in the Caption.

Unfortunatly the Validators are not started if I use setRequired.

Does anybody know if this will change soon?