InputElement
ZK Component Reference: Input Element
Input Element
- Demonstration: N/A
- Java API: org.zkoss.zul.impl.InputElement
- JavaScript API: zul.inp.InputWidget
Employment/Purpose
InputElement serves as a superclass for components that handle user key input. It is utilized by various input elements in ZK, such as:
InputElement provides features such as constraints, disabled state, maxlength, name attribute, readonly state, and more.
Developers are encouraged not to use this class directly, but rather utilize the inherited classes for specific input components.
Example
The following example demonstrates the usage of various input elements in a <grid>
layout:
<grid>
<rows>
<row>
UserName: <textbox value="Jerry" width="150px" />
</row>
<row>
Password: <textbox type="password" value="foo" width="150px" />
</row>
<row>
Phone: <intbox constraint="no negative,no zero" width="150px" value="12345678" />
</row>
<row>
Weight: <decimalbox format="###.##" value="154.32" width="150px" />
</row>
<row>
Birthday: <datebox id="db" width="150px" />
</row>
<row>
E-mail:
<textbox width="150px" value="zk@zkoss.org"
constraint="/.+@.+\.[a-z]+/: Please enter an e-mail address" />
</row>
</rows>
</grid>
Try it
Validation
There are two ways to validate the value entered by a user in ZK Input Elements: using Constraint or throwing WrongValueException.
Constraint
An input element in ZK can be associated with a Constraint to validate the user-entered value. ZK provides a default implementation called SimpleConstraint, which can handle various conditions.
Built-in Constraints
ZK allows specifying conditions using constraints such as no empty
and no negative
. Here are some of the available values for the constraint
attribute:
Condition | Description |
---|---|
no empty |
Empty values are not allowed. |
no future |
Date in the future is not allowed. |
no negative |
Negative numbers are not allowed. |
no past |
Date in the past is not allowed. |
no positive |
Positive numbers are not allowed. |
no today |
Today is not allowed. |
no zero |
Zero numbers are not allowed. |
between yyyyMMdd and yyyyMMdd |
Dates allowed only within a specified range. For example, <datebox constraint="between 20231225 and 20241203"/> |
after yyyyMMdd |
Dates allowed after the specified date. For example, <datebox constraint="after 20231225"/> |
before yyyyMMdd |
Dates allowed before the specified date. For example, <datebox constraint="before 20231225"/> |
end_before end_after after_start after_end … |
Specifies the position of the error box. Please refer to Popup for all allowed positions. For example, <textbox constraint="no empty, end_after"/><textbox constraint="no empty, start_before"/> |
For example,
<textbox constraint="no empty"/>
<intbox constraint="no negative,no zero"/>
Try it
Regular Expression
To specify a regular expression, use /
to enclose it.
For example:
<textbox constraint="/.+@.+\.[a-z]+/"/>
Notice that the above statement is XML, so do not use \\
to specify a backslash. On the other hand, it is required, if writing in Java:
new Textbox().setContraint("/.+@.+\\.[a-z]+/");
Try it
Flags
Since: 9.6.0
ZK supports using flags with regular expressions. Flags available include:
i
: Ignore casem
: Multilines
: DotAllu
: Unicode
For example:
<textbox constraint="/[A-Z]{3}/i"/>
Try it
Notice: the regular expression will always use global match no matter if the g flag is added or not.
Multiple Constraints
Combine regular expressions with other constraints by separating them with a comma. You can also customize the error message by appending the constraint with a colon and the desired message when it fails.
Example:
<textbox constraint="/.+@.+\.[a-z]+/: e-mail address only"/>
<datebox constraint="no empty, no future: now or never"/>
of course, it supports multiple custom messages
<intbox constraint="no negative: forbid negative, no positive: forbid positive" />
Try it
i18n Error Message
To support multilingual applications, you can use the l
function in ZK to display internationalized error messages. For example, you can set an error message for a textbox constraint as shown below:
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c"?>
<textbox constraint="/.+@.+\.[a-z]+/: ${c:l('err.email.required')}"/>
Escape a Comma
Since: 8.0.0
In cases where a longer sentence with a comma separator is required, you can enclose the sentence with curly braces. This ensures that the comma is treated as part of the sentence rather than a separator. For example:
<textbox constraint="no empty: {Sorry, no empty allowed}, /.+@.+\.[a-z]+/: email only"></textbox>
Scrollable Error Message
If you need to display an error message box that moves with scrolling, you can use the data-scrollable
attribute. This attribute allows the error message box to remain visible even when the page is scrolled.
Custom Constraint
Developers can create custom constraints by implementing the Constraint interface. This custom constraint can then be applied to input elements.
Example Java Implementation:
public class EvenNumberConstraint implements Constraint {
public void validate(Component comp, Object value) throws WrongValueException {
if (value != null && new Integer(value.toString()).intValue() % 2 == 1)
throw new WrongValueException(comp, "Only even numbers are allowed, not "+value);
}
}
To specify it to the constraint property, you have to instantiate it first by use of the new
function as shown below.
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c"?>
<textbox constraint="${c:new('foo.EvenNumberConstraint')}"/>
Display Error Message in Custom Way
For a more customized approach to displaying error messages, developers can implement the CustomConstraint interface along with the Constraint interface. This allows for a tailored error message presentation.
<window title="Custom Constraint" border="normal">
<zscript><![CDATA[
class MyConst implements Constraint, CustomConstraint {
//Constraint//
public void validate(Component comp, Object value) {
if (value == null || ((Integer)value).intValue() < 100)
throw new WrongValueException(comp, "At least 100 must be specified");
}
//CustomConstraint//
public void showCustomError(Component comp, WrongValueException ex) {
errmsg.setValue(ex != null ? ex.getMessage(): "");
}
}
Constraint ctt = new MyConst();
]]>
</zscript>
<hlayout>
Enter a number at least 100:
<intbox constraint="${ctt}" />
<label id="errmsg" />
</hlayout>
</window>
And, here is the result
Try it
Validate at Client for Better Responsiveness
To enhance responsiveness, developers can validate constraints at the client-side using the ClientConstraint interface in conjunction with the Constraint interface.
Note: The default constraint (SimpleConstraint) validates all constraints at the client side
WrongValueException
The WrongValueException can be thrown in various situations to handle validation errors. For instance, it can be used to validate user input when a login button is pressed.
Example Java Implementation:
public class CustomValidationComposer extends SelectorComposer {
@Wire
private Textbox username;
@Wire
private Textbox password;
@Listen("onClick = #login")
public void doLogin() {
username.clearErrorMessage();
if (validate(username, password)) {
// success
} else {
throw new WrongValueException(username, "Not a valid username or password. Please retry.");
}
}
}
However, notice that you have to clear the error message manually by invoking InputElement.clearErrorMessage(). Otherwise, the error message will remain there unless Textbox.setValue(String) is called.
Properties
Inplace
In-place editing functionality can be enabled for input elements like combobox, textbox, datebox, etc.
Example:
<grid width="500px">
<rows>
<row>
Textbox:
<textbox inplace="true" value="Click me" />
</row>
<row>
Combobox:
<combobox inplace="true" value="Click me" />
</row>
</rows>
</grid>
Try it
Instant
Since: 6.0.0
Introduced in ZK version 6.0.0, instant mode enables the onChange
event to be triggered as the user types in the input field, similar to the onChanging
event. The value is immediately updated on the server side and synchronized between the client and server.
The default value: false
Placeholder
Since: 6.5.0
Starting from ZK 6.5, input elements support HTML5 placeholder text. This feature is useful for providing users with guidance on what should be entered in the input field.
For example,
<textbox placeholder="Please type some text" />
InputAttributes
Since: 8.6.1
Introduced in ZK version 8.6.1, input elements can now have additional attributes set for the input HTML tag in the component. These attributes can be defined as a Map or a String with name-value pairs separated by “;
”.
For example,
<bandbox inputAttributes="${map}"></bandbox>
<datebox inputAttributes="autocorrect=off;spellcheck=true"></datebox>
Try it
Supported Events
Name | Event Type | Description |
---|---|---|
onChange |
Event: InputEvent | Indicates that the content of an input component has been modified by the user. |
onChanging |
Event: InputEvent | Indicates that the user is changing the content of an input component. The content is not changed until onChange is received. Use InputEvent.getValue() to retrieve the changed value. |
onSelection |
Event: SelectionEvent | Indicates that the user is selecting a portion of the text of an input component. Allows retrieval of the start and end position of the selected text. |
onFocus |
Event: Event | Indicates when a component gains focus. Event listeners execute at the server, potentially changing focus at the client. |
onBlur |
Event: Event | Indicates when a component loses focus. Event listeners execute at the server, potentially changing focus at the client. |
onError |
Event: ErrorEvent | Indicates when a component triggers a validation error. |
Supported Children
*NONE
: This component does not support any child components.
Browser Limitations
Browser | Description |
---|---|
iOS Safari / Chrome | In iOS Safari and Chrome browsers, there is a specific behavior related to input elements. In mobile Safari, users need to explicitly tap on the elements within the web view to display the keyboard. This behavior impacts how users interact with input elements on mobile devices. For example, <pre> <textbox id="test"/> </pre> |