10 Validate and Convert Input
oj-combobox
, oj-input*
,
and oj-text-area
. You can use them as is or customize them for
validating and converting input in your Oracle JET app.Some editable elements such as oj-checkboxset
, oj-radioset
, and oj-select
have a simple attribute for required
values that implicitly creates a built-in validator.
Note:
Theoj-input*
mentioned above refers to the family of input components such as oj-input-date-time
, oj-input-text
, and oj-input-password
, among others.
About Oracle JET Validators and Converters
Oracle JET provides converter classes that convert user input strings into the data type expected by the app and validator classes that enforce a validation rule on those input strings.
For example, you can use Oracle JET's IntlDateTimeConverter
to
convert a user-entered date to a Date
object for use by the app's
ViewModel and then use DateTimeRangeValidator
to validate that
input against a specified time range. You can also use converters to convert
Date
or Number
objects to a string suitable
for display or convert color object formats.
To retrieve the converter or validator factory for a registered type, Oracle JET provides the Validation
class which includes methods to register and retrieve converter and validator factories.
If the converters or validators included in Oracle JET are not sufficient for your
app, you can create custom converters or validators. Optionally, you can provide a
custom factory that implements the contract for a converter using
ConverterFactory
or a validator using
ValidatorFactory
and register the converter or validator with
the Validation
class. The Validation
class enables
you to access your custom converter or validator using the same mechanisms as you
would use with the Oracle JET standard converters and validators.
About Validators
All Oracle JET editable elements support a value
attribute and provide UI elements that allow the user to enter or choose a value. These elements also support other attributes that page authors can set that instruct the element how it should validate its value.
An editable element may implicitly create a built-in converter and/or built-in validators for its normal functioning when certain attributes are set.
For example, editable elements that support a required
property create the required validator implicitly when the property is set to true
. Other elements like oj-input-date
, oj-input-date-time
, and oj-input-time
create a datetime converter to implement its basic functionality.
About the Oracle JET Validators
The following table describes the Oracle JET validators and provides links to the API documentation:
Validator | Description | Link to API | Module |
---|---|---|---|
|
Validates that the input date is between two dates, between two times, or within two date and time ranges |
|
|
|
Validates that the input date is not a restricted date |
|
|
|
Validates that an input string is within a specified length |
|
|
|
Validates that an input number is within a specified range |
|
|
|
Validates that the regular expression matches a specified pattern |
|
|
|
Validates that a required entry exists |
|
About Oracle JET Component Validation Attributes
The attributes that a component supports are part of its API, and the following validation specific attributes apply to most editable elements.
Element Attribute | Description |
---|---|
|
When specified, the |
|
When specified on |
|
When specified on an Oracle JET element like |
|
When specified on an Oracle JET element like |
|
When specified on an Oracle JET element like |
|
When specified, it displays placeholder values in most elements. |
|
When specified on an Oracle JET element, the element creates an implicit required validator. |
|
When specified, the element uses these validators along with the implicit validators to validate the UI value. Can be implemented with |
Some editable elements do not support specific validation attributes as they might be irrelevant to its intrinsic functioning. For example, oj-radioset
and oj-checkboxset
do not support a converter attribute since there is nothing for the converter to convert. For an exact list of attributes and how to use them, refer to the Attributes
section in the element’s API documentation. For Oracle JET API documentation, see API
Reference for Oracle® JavaScript Extension Toolkit (Oracle JET). Select the component you're interested in viewing from the API list.
About Oracle JET Component Validation Methods
Oracle JET editable elements support the following methods for validation purposes. For details on how to call this method, its parameters and return values, refer to the component’s API documentation.
Element Method | Description |
---|---|
|
Use this method when the DOM the element relies on changes, such as the help attribute tooltip on an |
|
Use this method to reset the element by clearing all messages and messages attributes - |
|
Use this method to validate the component using the current display value. |
For details on calling a element's method, parameters, and return values, See the Methods
section of the element's API documentation in API
Reference for Oracle® JavaScript Extension Toolkit (Oracle JET). You can also find detail on how to register a callback for or bind to the event and for information about what triggers the events. Select the component you're interested in viewing from the API list.
About Converters
The Oracle JET converters include date, date-time, number, and color converters and are described in the following table.
Converter | Description | Link to API |
---|---|---|
|
Converts Color object formats |
|
|
Converts a string to a |
|
|
Converts a string to a number or formats a number or |
|
|
Converts a date-only ISO string to a formatted string or a string to a date-only ISO string |
About Oracle JET Component Converter Options
Oracle JET Converters use the options
attribute to allow a range of formatting options for color, number, date, and date-time values.
Color Converters
Color converters support the following options.
Option Name | Description |
---|---|
|
Sets the format of the converted color specification. Allowed values are "rgb" (default), "hsl", "hsv" "hex", and "hex3" (3 digit hex code). |
For an exact list of options and methods and how to use them, refer to API documentation of the ColorConverter
class. See ColorConverter.
Number Converters
Number converters support a number of options that can be used to format decimal numbers, currency, percentages, or units. Some of the important options are:
Option Name | Description |
---|---|
|
Sets the style of number formatting. Allowed values are "decimal" (default), "currency", "percent" or "unit". For decimals, percentages, and units, the locale-appropriate symbols are used for decimal characters (point or comma) and grouping separators (if grouping is enabled). |
|
Mandatory when |
|
Allowed values are "code", "name", and "symbol" (default). When style is currency , this option specifies if the currency is displayed as its name (such as Euro ) an ISO 4217 alphabetic currency code (such as EUR ), or the commonly recognized symbol (such as € ).
|
|
Mandatory when Use this option to format digital units like |
|
Sets the minimum number of digits before the decimal place. The number is padded with leading zeros if it would not otherwise have enough digits. Allowed values are any integer from 1 to 21. |
|
Sets the minimum number of digits after the decimal place. The number is padded with trailing zeros if it would not otherwise have enough digits. Allowed values are any integer from 0 to 20. |
|
Sets the maximum number of digits after the decimal place. The number is rounded if it has more than the set maximum number of digits. Allowed values are any integer from 0 to 20. |
|
Sets a pattern to use for the number, overriding other options. The pattern uses the symbols specified in the Unicode CLDR for numbers, percent, and currency formats. For the currency format, the For the percentage format, if the For the decimal or exponent patterns, the example is {pattern: "#,##0.00"} or {pattern: "0.##E+0"}. |
|
Specifies the rounding behavior. Allowed values are |
|
Specifies whether or not to round during parse. Defaults to false; the number converter rounds during format but not during parse. |
For an exact list of options and methods and how to use them, refer to API documentation of the IntlNumberConverter
class. See IntlNumberConverter.
The Oracle JET Cookbook includes implementations of the options discussed here. See Number Converter.
DateTime Converters
DateTime converters support a wide array of options that can be used to format date and time values in all common styles across locales. Some of the important options are:
Option Name | Description |
---|---|
|
Allowed values are the strings |
|
Allowed values are the strings |
|
Allowed values are the strings |
|
Determines the standard date and/or time format lengths to use. Allowed values are "date", "time", "datetime". When set, a value for |
|
Specifies the standard date format length to use when |
|
Specifies the standard time format length to use when |
|
Allowed values are the strings |
|
Allowed values are the strings |
|
Allowed values are the strings |
For an exact list of options and methods and how to use them, refer to API documentation of the IntlDateTimeConverter
class. See IntlDateTimeConverter.
The Oracle JET Cookbook includes implementations of the options discussed here. See DateTime Converter.
Date Converters
Date converters support options that can be used to format date-only values in all common styles across locales. The LocalDateConverter
has fewer options than the IntlDateTimeConverter
, with no options related to time or timezone; however, it is efficient and flexible when parsing user input into formatted date strings.
Option Name | Description |
---|---|
|
Specifies the standard date format length to use. Allowed values are: |
locale |
Specifies a locale to be used by this converter instance. If this option is not provided, the converter will call |
For an exact list of options and methods and how to use them, refer to API documentation of the LocalDateConverter
class. See LocalDateConverter.
About Oracle JET Converters
The Oracle JET color, date, date-time, and number converters, ColorConverter
, LocalDateConverter
, IntlDateTimeConverter
, and IntlNumberConverter
, extend the Converter
object which defines a basic contract for converter implementations.
The converter API is based on the ECMAScript Internationalization API specification (ECMA-402 Edition 1.0) and uses the Unicode Common Locale Data Repository (CLDR) for its locale data. Both converters are initialized through their constructors, which accept options defined by the API specification. For additional information about the ECMA-402 API specification, see https://www.ecma-international.org/publications-and-standards/standards/ecma-402/. For information about the Unicode CLDR, see http://cldr.unicode.org.
The Oracle JET implementation extends the ECMA-402 specification by introducing additional options, including an option for user-defined patterns. For the list of additional options, see the ColorConverter, IntlDateTimeConverter, IntlNumberConverter, and LocalDateConverter API documentation.
Note:
The bundles that hold the locale symbols and data used by the Oracle JET converters
are downloaded automatically based on the locale set
on the page when using RequireJS and the
ojs/ojvalidation-datetime
or
ojs/ojvalidation-number
module.
If your app does not use RequireJS, the locale data
will not be downloaded automatically.
You can use the converters with an Oracle JET component or instantiate and use them directly on the page.
The Oracle JET Cookbook includes implementations of the options discussed here. See:
Use Oracle JET Converters with Oracle JET Components
Oracle JET elements that accept user input, such as
oj-input-date
, already include an implicit converter that is used when
parsing user input. However, you can also specify an explicit converter on the element that
will be used instead when converting data from the model for display on the page, and vice
versa. An explicit converter is required if you want to include timezone data.
For example, the following code sample shows a portion of a form containing an
oj-input-date
component that uses the default converter supplied by the
component implicitly. The highlighted code shows the oj-input-date
component.
<oj-form-layout id="datetime-converter-example">
<oj-input-date id="date1" value="{{date}}"
label-hint="input date with no converter"
help.instruction="enter a date in your preferred format and we
will attempt to figure it out">
</oj-input-date>
</oj-form-layout>
The script to create the view model for this example is shown below.
import * as ko from 'knockout';
import 'ojs/ojformlayout';
import 'ojs/ojdatetimepicker';
import { IntlConverterUtils } from 'ojs/ojconverterutils-i18n';
class DemoViewModel {
date: ko.Observable<string>;
constructor() {
this.date = ko.observable
(IntlConverterUtils.dateToLocalIsoDateString(new Date()));
}
}
export = IncidentsViewModel;
define(['knockout', 'ojs/ojconverterutils-i18n', 'ojs/ojknockout',
'ojs/ojdatetimepicker', 'ojs/ojformlayout'],
function (ko, ConverterUtilsI18n) {
function DemoViewModel() {
const date = new Date();
this.value = ko.observable
(ConverterUtilsI18n.IntlConverterUtils.dateToLocalIso(date));
}
return DemoViewModel;
}
);
When the user runs the page, the oj-input-date
element
displays an input field with the expected date format. In this example, the element also
displays a hint when the user hovers over the input field, and it displays a calendar when
the user clicks in the input field. If the user inputs data that is not in the expected
format, the built-in converter displays an error message with the expected format.
The error that the converter throws when there are errors during parsing or
formatting operations is represented by the ConverterError
object, and
the error message is represented by an object that duck-types Message
.
The messages that Oracle JET converters use are resources that are defined in the
translation bundle included with Oracle JET.
For more information about messaging in
Oracle JET, see Work with User Assistance.
You can also specify the converter directly on the element's
converter
attribute, if it exists. The code excerpt below defines
another oj-input-date
element on the sample form and specifies the
IntlDateTimeConverter
converter with options that will convert the
user's input to a numeric
year, long
month, and
numeric
day according to the conventions of the locale set on the page.
The options
parameter is an object literal that contains the ECMA-402
options as name-value pairs.
<div class="oj-flex">
<div class="oj-flex-item">
<oj-label for="date2">input date</oj-label>
</div>
<div class="oj-flex-item">
<oj-input-date
id="date2"
value="{{date}}"
help.instruction="enter a date in your preferred format and we will attempt
to figure it out"
converter='{ "type":"datetime",
"options": {"year": "numeric", "month": "long",
"day": "numeric"}}'>
</oj-input-date>
</div>
</div>
When the user runs the page in the en-us
locale, the
oj-input-date
element displays an input field that expects the user's
input date to be in the mmmm d, yyyy
format. The converter will accept
alternate input if it makes sense, such as 18/07/17
(MM/dd/yy)
, and perform the conversion, but it will throw an error if
it cannot parse the input. For details about Oracle JET converters and lenient parsing
support, see About Oracle JET Converters Lenient Parsing.
Parsing of narrow era, weekday, or month name is not supported because of
ambiguity in choosing the right value. For example, if you initialize the date-time
converter with options {weekday: 'narrow', month: 'narrow', day: 'numeric', year:
'numeric'}
, then for the en-US locale, the converter will format the date
representing May 06, 2014
as T, M 6, 2014
, where
T
represents Tuesday. If the user inputs T, M 6, 2014
,
the converter can't determine whether the user meant
Thursday
,
March
6, 2014
or Tuesday
,
May
6, 2014
. Therefore, Oracle JET
expects that user input be provided in either their short or long forms, such as
Tues, May 06, 2014
.
For additional details about the IntlDateTimeConverter
and
IntlNumberConverter
component options, see IntlDateTimeConverter and IntlNumberConverter.
About Oracle JET Converters Lenient Parsing
The Oracle JET converters support lenient number and date parsing when the user input does not exactly match the expected pattern. The parser does the lenient parsing based on the leniency rules for the specific converter.
IntlDateTimeConverter
provides parser leniency when converting user input to a date and enables the user to:
-
Input any character as a separator irrespective of the separator specified in the associated pattern. For example, if the expected date pattern is set to
y-M-d
, the date converter will accept the following values as valid:2020
-
06
-
16
,2013
/
06
-
16
, and2020
aaa
06
xxx
16
. Similarly, if the expected time pattern is set toHH:mm:ss
, the converter will accept the following values as valid:12
.
05
.35
. -
Specify a 4-digit year in any position relative to day and month. For example, both
11-
2013
-16
and16-11-
2013
are valid input values. -
Swap month and day positions, as long as the date value is greater than 12 when working with the Gregorian calendar. For example, if the user enters
2020-16-06
wheny-M-d
is expected, the converter will autocorrect the date to2020-06-16
. However, if both date and month are less or equal to 12, no assumptions are made about the day or month, and the converter parses the value against the exact pattern. -
Enter weekday and month names or mix short and long names anywhere in the string. For example, if the expected pattern is
E, MMM, d, y
, the user can enter any of the following dates:Tue, Jun 16 2020 Jun, Tue 2020 16 2020 Tue 16 Jun
-
Omit weekdays. For example, if the expected pattern is
E, MMM d, y
, then the user can enterJun 16, 2020
, and the converter autocorrects the date toTuesday, Jun 16, 2020
. Invalid weekdays are not supported. For instance, the converter will throw an exception if the user entersWednesday, Jun 16, 2020
.
IntlNumberConverter
supports parser leniency as follows:
-
If the input does not match the expected pattern, Oracle JET attempts to locate a number pattern within the input string. For instance, if the pattern is
#,##0.0
, then the input stringabc-123.45de
will be parsed as-123.45
. -
For the currency style, the currency symbol can be omitted. Also, the negative sign can be used instead of a negative prefix and suffix. As an example, if the
pattern
option is specified as"\u00a4#,##0.00;(\u00a4#,##0.00)"
, then($123)
,(123)
, and-123
will be parsed as-123
. -
When the style is percent, the percent sign can be omitted. For example,
5%
and5
will both be parsed as0.05
.
Understand Time Zone Support in Oracle JET
By default, the oj-input-date-time
and oj-input-time
elements and IntlDateTimeConverter
support only local time zone input. You can add time zone support by including the ojs/ojtimezonedata
module and creating a converter with the desired pattern.
Oracle JET supports time zone conversion and formatting using the following patterns:
Token | Description | Example |
---|---|---|
z, zz, zzz |
Abbreviated time zone name, format support only |
PDT, PST |
zzzz |
Full time zone name, format support only |
Pacific Standard Time, Pacific Daylight Time |
Z, ZZ, ZZZ |
Sign hour minutes |
-0800 |
X |
Sign hours |
-08 |
XX |
Sign hours minutes |
-0800 |
XXX |
Sign hours:minutes |
-08:00 |
VV |
Time Zone ID |
America/Los Angeles |
The image below shows the basic oj-input-date-time
element
configured for time zone support. In this example from the Oracle JET Cookbook the component
is converted using the Z pattern.
The oj-input-date-time
element is initialized with its converter
attribute, in this case a method named dateTimeConverter
.
<oj-input-date-time
id="timezone"
value="{{dateTimeValue}}"
converter="[[dateTimeConverter]]">
</oj-input-date-time>
The viewModel contains the dateTimeConverter()
definition. Note that
you must also add the ojs/ojconverter-datetime
module to use its DateTimeConverter
API. The Oracle JET Cookbook includes implementations
of the options discussed here. See
Input
Date and Time - Time Zone.
Use Custom Converters in Oracle JET
You can create custom converters in Oracle JET by extending
Converter
or by duck typing it. You can also create a custom converter
factory to register the converter with Oracle JET and make it easier to instantiate the
converter.
Custom converters can be used with Oracle JET components, provided they don't violate the integrity of the component. As with the built-in Oracle JET converters, you can also use them directly on the page.
The following image shows an implementation of a custom converter that converts the
current date to a relative term. The Schedule For
column uses a
RelativeDateTimeConverter
to convert the date that the page is run in the
en-US
locale to display Today
,
Tomorrow
, and the date in two days.
To create and use a custom converter in Oracle JET:
Use Oracle JET Converters Without Oracle JET Components
If you want to use a converter without binding it to an Oracle JET component, create the converter using the constructor for the converter of your choice.
The Oracle JET Cookbook includes a demo that shows how to use the number and date time converters directly in your pages without binding them to an Oracle JET component. In the demo image, the salary is a number formatted as currency, and the start date is an ISO string formatted as a date.
The viewModel defines a salaryConverter
method to format a number as currency
and a dateConverter
that formats the start date using the date format style
and medium date format while the view HTML binds to the returned values, as shown in the
following snippet for Amy Flanagan’s salary and start date.
. . .
<p>Product Manager</p>
<span style="white-space:nowrap;"><b>Salary</b>:
<span>
<oj-bind-text value="[[amySalary]]"></oj-bind-text>
</span>
</span>
<br />
<span style="white-space:nowrap;"><b>Joined</b>:
<span>
<oj-bind-text value="[[amyStartDate]]"></oj-bind-text>
</span>
. . .
The Oracle JET Cookbook includes implementations of the options discussed here. See Converters Factory.
About Oracle JET Validators
Oracle JET validators provide properties that allow callers to customize the validator instance. The properties are documented as part of the validators’ API. Unlike converters where only one instance of a converter can be set on an element, page authors can associate one or more validators with an element.
When a user interacts with the element to change its value, the validators associated with the element are run in order. When the value violates a validation rule, the value
attribute is not populated, and the validator highlights the element with an error.
You can use the validators with an Oracle JET element or instantiate and use them directly on the page.
Use Oracle JET Validators with Oracle JET Components
Oracle JET editable elements, such as oj-input-text
and oj-input-date
, set up validators both implicitly, based on certain attributes they support such as required
, min
, max
, and so on, and explicitly by providing a means to set up one or more validators using the component's validators
attribute. As with the Oracle JET converters, the validators
attribute can be specified either using JSON array notation or can be an array of actual validator instances.
For example, the following code sample shows a portion of a form containing an oj-input-date
element that uses the default validator supplied by the component implicitly. The highlighted code shows the HTML5 attribute set on the oj-input-date
element. When the oj-input-date
reads the min
attribute, it creates the implicit DateTimeRangeValidator
.
<oj-form-layout id="validator-example">
<oj-input-date
id="dateTimeRange1"
value="{{dateValue1}}"
min="2000-01-01T08:00:00.000"
help.instruction="enter a date that falls in the current
millenium and not greater than today's date."
max="[[todayIsoDate]]"
label-hint="'min' attribute and 'max' option">
</oj-input-date>
</oj-form-layout>
The script to create the view model for this example is shown below.
import * as ko from "knockout";
import * as ConverterUtilsI18n from "ojs/ojconverterutils-i18n";
import "ojs/ojknockout";
import "ojs/ojformlayout";
import "ojs/ojdatetimepicker";
class DemoViewModel {
dateValue1: ko.Observable<string>;
dateValue2: ko.Observable<string>;
todayIsoDate: ko.Observable<string>;
milleniumStartIsoDate: ko.Observable<string>;
constructor() {
this.dateValue1 = ko.observable("");
this.dateValue2 = ko.observable("");
this.todayIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.dateToLocalIso(new Date())
);
this.milleniumStartIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.dateToLocalIso(new Date(2000, 0, 1))
);
}
}
export = DemoViewModel;
define([
"knockout",
"ojs/ojconverterutils-i18n",
"ojs/ojknockout",
"ojs/ojdatetimepicker",
"ojs/ojformlayout",
], function (
ko,
ConverterUtilsI18n
) {
function DemoViewModel() {
this.dateValue1 = ko.observable();
this.dateValue2 = ko.observable();
this.todayIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.dateToLocalIso(new Date())
);
this.milleniumStartIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.dateToLocalIso(new Date(2000, 0, 1))
);
}
return DemoViewModel;
});
When the user runs the page, the oj-input-date
element
displays an input field with a calendar icon. The help.instruction
attribute set on the element displays below the input field when you click on the input
field. If you input data that is not within the expected range, the built-in validator
displays an error message with the expected range.
The error thrown by the Oracle JET validator when validation fails is
represented by the ValidatorError
object, and the error message is
represented by an object of type Message
. The messages and hints that
Oracle JET validators use when they throw an error are resources that are defined in the
translation bundle included with Oracle JET. For more information about
messaging in Oracle JET, see Work with User Assistance.
You can also specify the validator on the element's
validators
attribute, if it exists. The code sample below adds another
oj-input-date
element to the sample form and calls a function which
specifies the DateTimeRangeValidator
validator
(dateTimeRange
) in the validators
attribute.
<oj-form-layout id="validator-example">
<oj-input-date
id="dateTimeRange2"
value="{{dateValue2}}"
validators="[[validators]]"
help.instruction="enter a date that falls in the current millenium and
not greater than today's date."
label-hint="'dateTimeRange' type in 'validators' option">
</oj-input-date>
</oj-form-layout>
The code below shows the additions to the viewModel with options that set the valid minimum and maximum dates and a hint that displays when the user sets the focus in the field.
import * as ko from "knockout";
import * as ConverterUtilsI18n from "ojs/ojconverterutils-i18n";
import AsyncDateTimeRangeValidator
= require("ojs/ojasyncvalidator-datetimerange");
import * as DateTimeConverter from "ojs/ojconverter-datetime";
import "ojs/ojknockout";
import "ojs/ojformlayout";
import "ojs/ojdatetimepicker";
class DemoViewModel {
dateValue1: ko.Observable<string>;
dateValue2: ko.Observable<string>;
todayIsoDate: ko.Observable<string>;
milleniumStartIsoDate: ko.Observable<string>;
validators: ko.Computed<AsyncDateTimeRangeValidator<string>[]>;
constructor() {
this.dateValue1 = ko.observable("");
this.dateValue2 = ko.observable("");
this.todayIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.dateToLocalIso(new Date())
);
this.milleniumStartIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.
dateToLocalIso(new Date(2000, 0, 1))
);
this.validators = ko.computed(() => {
return [
new AsyncDateTimeRangeValidator({
max: this.todayIsoDate(),
min: this.milleniumStartIsoDate(),
hint: {
inRange: "Enter a date that falls in the
current millennium.",
},
converter: new DateTimeConverter.IntlDateTimeConverter({
day: "2-digit",
month: "2-digit",
year: "2-digit",
}),
}),
];
});
}
}
export = DemoViewModel;
define([
"knockout",
"ojs/ojconverterutils-i18n",
"ojs/ojasyncvalidator-datetimerange",
"ojs/ojconverter-datetime",
"ojs/ojknockout",
"ojs/ojdatetimepicker",
"ojs/ojformlayout",
], function (
ko,
ConverterUtilsI18n,
AsyncDateTimeRangeValidator,
DateTimeConverter
) {
function DemoViewModel() {
this.dateValue1 = ko.observable();
this.dateValue2 = ko.observable();
this.todayIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.
dateToLocalIso(new Date())
);
this.milleniumStartIsoDate = ko.observable(
ConverterUtilsI18n.IntlConverterUtils.
dateToLocalIso(new Date(2000, 0, 1))
);
this.validators = ko.computed(
function () {
return [
new AsyncDateTimeRangeValidator({
max: this.todayIsoDate(),
min: this.milleniumStartIsoDate(),
hint: {
inRange: "Enter a date that falls
in the current millennium.",
},
converter: new DateTimeConverter.
IntlDateTimeConverter({
day: "2-digit",
month: "2-digit",
year: "2-digit",
}),
}),
];
}.bind(this)
);
}
return DemoViewModel;
});
When the user runs the page for the en-US
locale, the
oj-input-date
element displays an input field that expects the user's
input date to be between 01/01/2000
and the current date. When entering a
date value into the field, the date converter will accept alternate input as long as it
can parse it unambiguously. This offers end users a great deal of leniency when entering
date values. For example, typing 1-2-3
will convert to a
Date
that falls on the 2nd day of January, 2003. If the
Date
value also happens to fall in the expected Date
range set in the validator, then the value is accepted. If validation fails, the component
displays an error.
Oracle JET elements can also use a regExp
validator. If the regular expression pattern requires a backslash, while specifying the
expression within an Oracle JET element, you need to use double backslashes. The options
that each validator accepts are specified in API
Reference for Oracle® JavaScript Extension Toolkit (Oracle JET).
The Oracle JET Cookbook contains the complete example discussed in this section as well as examples that show the built-in validators for date restrictions, length, number range, regular expression, and required fields. For details, see Validators.
For more information about Oracle JET component validation, see Understand How Validation and Messaging Works in Oracle JET Editable Components.
Use Custom Validators in Oracle JET
You can create custom validators in Oracle JET by extending Validator
or by duck typing it.
Custom validators can be used with Oracle JET components, provided they don't violate the integrity of the component. As with the built-in Oracle JET validators, you can also use them directly on the page. For information about messaging in Oracle JET, see Use the messages-custom Attribute. The following image shows a custom validator that displays an error message if the user’s password doesn’t match.
To create and use a custom validator in Oracle JET:
About Asynchronous Validators
Oracle JET input components support asynchronous server-side validation via the validators
attribute. That means you can check input values against server data without the need to submit a form or refresh a page.
Two example scenarios illustrate where you can use asynchronous server-side validation:
- In a form that collects new user data, you validate input in an email field to check if the input value has been registered previously.
- Set number range validators that check against volatile data. For example, on an e-commerce website, you can check the user’s cart against the available inventory and inform the user if the goods are unavailable without them submitting the cart for checkout.
The Oracle JET Cookbook has a sample that uses the validators
attribute and dummy data to simulate server-side validation.
The following code shows an oj-input-text
element with the
validators
attribute set to validators
and
asyncValidator
observables in the viewModel code. The
validators
attribute must be of type AsyncValidator
to
fulfill the API contract required to create the asynchronous validator.
<oj-form-layout id="fl1">
<oj-c-input-text
id="input-text"
required
label-hint="Quantity Limit"
on-valid-changed="[[validChangedListener]]"
validators="[[[validators, asyncValidator]]]"
value="{{quantityLimit}}"
converter="[[currencyConverter]]">
</oj-c-input-text>
</oj-form-layout>
The viewModel code includes a number range validator created in the
asyncValidator object that returns a Promise. A Promise object represents a value that may not
be available yet, but will be resolved at some point in the future. In asynchronous
validation, the AsyncValidator.validate()
function returns a Promise that
evaluates to Boolean true
if validation passes and if validation fails, it
returns an Error. For more information, see the validators
attribute section
of
ojInputText or see Promise (MDN).
The Oracle JET Cookbook includes implementations of the options discussed here. See Async Validators.