Reputation:
I am trying to create a form in ExtJS with a time field. This time field should only accept full hours.
It is configured like this:
{
name: 'validFromTime',
fieldLabel: 'Valid From Time',
xtype: 'timefield',
increment: 60,
allowBlank: false
}
The 60 minute increment only affects the picker UI, but not the validation. Thus, I have to validate myself to prevent the user from typing something like 1:20 AM into the time field.
I tried to do that with the following regex config:
{
name: 'validFromTime',
fieldLabel: 'Valid From Time',
xtype: 'timefield',
increment: 60,
regex: /^([1-9]|1[0-2]):(00)\s([A|P]M)$/,
invalidText: 'Must be a full hour in format "1:00 AM/PM".',
allowBlank: false
}
According to this online regex checker, this regex is correct: https://regex101.com/r/uR9sM0/1
However, ExtJS now always marks this field as invalid, even when the user selects a correct time like 11:00 AM.
To isolate the problem, I tried to match a little bit less. The most I can get working is this:
/([1-9]|1[0-2]):00.*/
As soon as I add any of the other parts, like the ^ or the \s, it doesn't work anymore. Any ideas on what I am missing?
Upvotes: 3
Views: 1055
Reputation: 4047
As mentioned in the comments already, the underlying value of a time field is a Date object. Therefore I'd recommend to validate the Date object instead of the input text, not only because it's much easier than building a regex but also because the timefield recognizes some additional input patterns other than the displayed format (see the format
and altFormats
config options) which would be prevented altogether when using a regex validation.
You can use the validator
config option to provide a function used for your custom validation(s) which will be run in addition to the field's built-in validations:
validator: function() {
var value = this.getValue();
if (Ext.isDate(value) && value.getMinutes() !== 0) {
return 'Must be a full hour in format "1:00 AM/PM".';
}
return true;
}
Note that the check for the object type is mandatory, because value
will not be a date object if the field is unable to parse the user's input.
Fiddle: https://fiddle.sencha.com/#fiddle/pu2
Upvotes: 3