PDA

View Full Version : How to do conditional validation on combo box?



Beginner1971
18 Feb 2011, 6:06 AM
I have a problem that is conceptually pretty simple, but am having trouble finding a solution. Basically, I have a combo box which I want to be a required field BUT only if there are items in the list. IOW, if there's at least one item to select, the user must select one. However, if the list is empty, they don't have to select anything.

I can't set allowBlank to false in the config because that will always require a value.
I tried setting allowBlank dynamically, but this doesn't seem to work. Instead, when allowBlank is false, it still allows blanks.
I tried using plugin to do validation on blur. This only partially works. When the combo box loses focus, it will show the validation error message but when the user clicks submit, the error vanishes and form submits anyway.
I tried using a vtype. But vtypes only seem to perform validation if the combo box has a value. IOW, when the user hasn't typed or selected anything, the vtype isn't invoked.
Does anyone have any ideas?

emils
18 Feb 2011, 6:22 AM
may be you must "disable" this combo box... something like:



if (ComboboxStore.getCount()==0) {
Combobox.setDisabled(true);
}

mschwartz
18 Feb 2011, 6:25 AM
If your form has no file upload field, you can serialize the form yourself and do the exact kind of validation you require along the way.

By serialize the form, I mean:



var serialized = {
firstName: Ext.getCmp('firstName').getValue(),
lastName: Ext.getCmp('lastName').getValue()
...
};

if (serialized.firstName.trim().length == 0) {
alert('Enter a first name!');
}
// and so on.


Then Ext.Ajax.request() to POST your serialized results.

Condor
18 Feb 2011, 8:08 AM
A vtype doesn't get invoked for empty text fields, but the validator method does!

Beginner1971
18 Feb 2011, 8:33 AM
Thanks, that works. For the benefit of others reading this thread, here's my code:


var stateField = this.getForm().findField('StateCd');
if (stateField){
var store = stateField.getStore();
// unrelated code omitted
var count = store.getCount();
if (count){
stateField.setDisabled(false);
stateField.validate();
} else {
stateField.clearInvalid();
stateField.setDisabled(true);
}
}

Hopefully, our UX team won't complain about disabling the combo box. :)

Beginner1971
18 Feb 2011, 8:36 AM
Thanks, I didn't know about the validator method. I'll keep that in mind in case there are any issues complaints.