PDA

View Full Version : How to make a number field optional AND have min and max validation?



skcus_ahcnes
19 Feb 2015, 11:33 AM
I am using Sencha Architect 3.1.0 and ExtJS 5.0.

Objective:

I want a number field in the UI to be optional, but if a value is specified, it must be within a certain range.

Background:

It seems as though if I specify a minValue in the number field, it assumes that it's a required field, regardless of "allowBlank: true" or "allowNull: true". Specifying a "minValue" should not automatically make it required. Seems odd.

Also, in Sencha Architect, I don't seem to have an option to specify a Range validation on the model field. How can I add this?

I have a model with an int field as such:



{
type: 'int',
allowNull: true,
name: 'intField'
}


I have the form field specified as follows:



{
xtype: 'numberfield',
width: 400,
fieldLabel: 'Number must be between 1 and 50 (if specified)',
name: 'intField',
allowOnlyWhitespace: false,
allowDecimals: false,
allowExponential: false,
maxValue: 50,
minValue: 1
},

How can I make this work?

Thanks!

evant
19 Feb 2015, 11:47 AM
You need to specify allowBlank: true on the field:



Ext.onReady(function() {

var f = new Ext.form.field.Number({
renderTo: document.body,
fieldLabel: 'Number must be between 1 and 50 (if specified)',
allowBlank: true,
maxValue: 50,
minValue: 1
});

new Ext.button.Button({
renderTo: document.body,
text: 'Validate',
handler: function() {
console.log(f.validate());
}
});

});

skcus_ahcnes
19 Feb 2015, 11:54 AM
Using Architect, the allowBlank is already set to true because it's default and doesn't show up in the code. If I uncheck, it specifically says "allowBlank: false". If check it back on, it goes away.

skcus_ahcnes
19 Feb 2015, 1:04 PM
Actually, I figured something out. The 'allowOnlyWhitespace' documentation is as follows:


Specify false to automatically trim the value before validating the whether the value is blank. Setting this to false automatically sets allowBlank to false.

Defaults to: true

The name of this property and its behaviour are misleading. Allow Only Whitespace set to false should mean that if a user inputs only whitespace, do not allow the field to be valid. Instead, what's happening is that whitespace character is trimmed and then considered "blank", which makes sense. But the framework is setting allowBlank to false, for whatever reason, and this can cause unwanted behaviour.

This property should be renamed to "trimWhitespace" and not change the allowBlank property automatically... ever.

Also, if one property changes the behaviour of the another property, the other property should have it specified in its documentation as well. Currently, allowBlank does not document this behaviour.

Cheers!