InputElement"

From Documentation
 
(34 intermediate revisions by 7 users not shown)
Line 8: Line 8:
  
 
= Employment/Purpose =
 
= Employment/Purpose =
InputElement is a super class for components which prove user key input, such as
+
InputElement is a super class for components which handle user key input, such as
<tt>[[ZK_Component_Reference/Input/Textbox|textbox]],</tt>  
+
<code>[[ZK_Component_Reference/Input/Textbox|textbox]],</code>  
<tt>[[ZK_Component_Reference/Input/Intbox|intbox]],</tt>  
+
<code>[[ZK_Component_Reference/Input/Intbox|intbox]],</code>  
<tt>[[ZK_Component_Reference/Input/Decimalbox|decimalbox]],</tt>
+
<code>[[ZK_Component_Reference/Input/Decimalbox|decimalbox]],</code>
<tt>[[ZK_Component_Reference/Input/Doublebox|doublebox]]</tt>,  
+
<code>[[ZK_Component_Reference/Input/Doublebox|doublebox]]</code>,  
<tt>[[ZK_Component_Reference/Input/Datebox|datebox]]</tt>,  
+
<code>[[ZK_Component_Reference/Input/Datebox|datebox]]</code>,  
<tt>[[ZK_Component_Reference/Input/Timebox|timebox]]</tt>,  
+
<code>[[ZK_Component_Reference/Input/Timebox|timebox]]</code>,  
<tt>[[ZK_Component_Reference/Input/Spinner|spinner]]</tt>,  
+
<code>[[ZK_Component_Reference/Input/Spinner|spinner]]</code>,  
<tt>[[ZK_Component_Reference/Input/Combobox|combobox]]</tt>, and  
+
<code>[[ZK_Component_Reference/Input/Combobox|combobox]]</code>, and  
<tt>[[ZK_Component_Reference/Input/Bandbox|bandbox]]</tt>.
+
<code>[[ZK_Component_Reference/Input/Bandbox|bandbox]]</code>.
  
 
Some features are implemented in this class, such as constraint, disabled, maxlength, name, readonly, and so on.
 
Some features are implemented in this class, such as constraint, disabled, maxlength, name, readonly, and so on.
Line 55: Line 55:
 
= Validation =
 
= Validation =
  
There are two ways to validate the value entered by an user: implementing <javadoc>org.zkoss.zul.Constraint</javadoc> or throwing <javadoc>org.zkoss.zk.ui.WrongValueException</javadoc>.
+
There are two ways to validate the value entered by a user: implementing <javadoc>org.zkoss.zul.Constraint</javadoc> or throwing <javadoc>org.zkoss.zk.ui.WrongValueException</javadoc>.
  
 
== Constraint ==
 
== Constraint ==
  
An input element can be associated with a constraint (<javadoc>org.zkoss.zul.Constraint</javadoc>) to validate the value entered by an user. There is a default implementation called <javadoc>org.zkoss.zul.SimpleConstraint</javadoc> that can handle many conditions. If it is not enough, you can implement your own constraint, or throwing <javadoc>org.zkoss.zk.ui.WrongValueException</javadoc> as described in the next sections.
+
An input element can be associated with a constraint (<javadoc>org.zkoss.zul.Constraint</javadoc>) to validate the value entered by a user. There is a default implementation called <javadoc>org.zkoss.zul.SimpleConstraint</javadoc> that can handle many conditions. If it is not enough, you can implement your own constraint, or throw <javadoc>org.zkoss.zk.ui.WrongValueException</javadoc> as described in the next sections.
  
To use the default constraint, you could specify a list of conditions in <javadoc method="setConstraint(java.lang.String)">org.zkoss.zul.impl.InputElement</javadoc>, such as <tt>no positive</tt> and <tt>no empty</tt>. For example,
+
=== Built-in Constraints ===
 +
To use the default constraint, you could specify a list of conditions in <javadoc method="setConstraint(java.lang.String)">org.zkoss.zul.impl.InputElement</javadoc>, such as <code>no positive</code> and <code>no empty</code>. For example,
  
 
<source lang="xml">
 
<source lang="xml">
Line 68: Line 69:
 
</source>
 
</source>
  
To specify a regular expression, you could have to use <tt>/</tt> to enclose the regular expression as follows.
 
  
<source lang="xml">
+
{| class='wikitable' | width="100%"
<textbox constraint="/.+@.+\.[a-z]+/"/>
 
</source>
 
 
 
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:
 
 
 
<source lang="java">
 
new Textbox().setContraint("/.+@.+\\.[a-z]+/");
 
</source>
 
 
 
Notice that it is allowed to mix regular expression with other constraints by separating them with comma.
 
 
 
If you prefer to display an application dependent message instead of default one, you could append the constraint with colon and the message you want to display when failed.
 
 
 
<source lang="xml">
 
<textbox constraint="/.+@.+\.[a-z]+/: e-mail address only"/>
 
<datebox constraint="no empty, no future: now or never"/>
 
</source>
 
 
 
Notice that the error message, if specified, must be the last element and start with a colon.  To support multilingual, you could use [[ZUML Reference/EL Expressions/Core Methods/l|the l function]] as depicted in [[ZK Developer's Reference/Internationalization|ZK Developer's Reference]].
 
 
 
<source lang="xml">
 
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c"?>
 
<textbox constraint="/.+@.+\.[a-z]+/: ${c:l('err.email.required')}"/>
 
</source>
 
 
 
If you want to move an error message box by scrolling, please use [http://books.zkoss.org/wiki/ZUML_Reference/ZUML/Namespaces/Client_Attribute/Data-Scrollable data-scrollable attribute].
 
 
 
 
 
{| border='1px' | width="100%"
 
 
! Condition !! Description
 
! Condition !! Description
|+ The default constraints
+
|+ You can specify the following values at <code>constraint</code> attribute to apply them
 
|-
 
|-
 
| no empty
 
| no empty
Line 116: Line 87:
 
|-
 
|-
 
| no positive
 
| no positive
| Postive numbers are not allowed.
+
| Positive numbers are not allowed.
 
|-
 
|-
 
| no today
 
| no today
Line 125: Line 96:
 
|-
 
|-
 
| between ''yyyyMMdd'' and ''yyyyMMdd''
 
| between ''yyyyMMdd'' and ''yyyyMMdd''
| Date only allowed between the specified range. The format must be <tt>yyyyMMdd</tt>, such as  
+
| Date only allowed between the specified range. The format must be <code>yyyyMMdd</code>, such as  
 
<source lang="xml">
 
<source lang="xml">
 
<datebox constraint="between 20071225 and 20071203"/>
 
<datebox constraint="between 20071225 and 20071203"/>
Line 131: Line 102:
 
|-
 
|-
 
| after ''yyyyMMdd''
 
| after ''yyyyMMdd''
| Date only allowed after (and including) the specified date. The format must be <tt>yyyyMMdd</tt>, such as  
+
| Date only allowed after (and including) the specified date. The format must be <code>yyyyMMdd</code>, such as  
 
<source lang="xml">
 
<source lang="xml">
 
<datebox constraint="after 20071225"/>
 
<datebox constraint="after 20071225"/>
Line 137: Line 108:
 
|-
 
|-
 
| before ''yyyyMMdd''
 
| before ''yyyyMMdd''
| Date only allowed before (and including) the specified date. The format must be <tt>yyyyMMdd</tt>, such as  
+
| Date only allowed before (and including) the specified date. The format must be <code>yyyyMMdd</code>, such as  
 
<source lang="xml">
 
<source lang="xml">
 
<datebox constraint="before 20071225"/>
 
<datebox constraint="before 20071225"/>
Line 149: Line 120:
 
  after_end
 
  after_end
 
  ...
 
  ...
|Specifies the position of the error box. Please refer  to [[ZK Component Reference/Essential Components/Popup|Popup]]  for all allowed position.
+
|Specifies the position of the error box. Please refer  to [[ZK Component Reference/Essential Components/Popup|Popup]]  for all allowed positions.
 
<source lang="xml">
 
<source lang="xml">
 
<textbox constraint="no empty, end_after"/>
 
<textbox constraint="no empty, end_after"/>
Line 155: Line 126:
 
</source>
 
</source>
 
|}
 
|}
 +
 +
 +
 +
=== Regular Expression ===
 +
To specify a regular expression, you could have to use <code>/</code> to enclose the regular expression as follows.
 +
 +
<source lang="xml">
 +
<textbox constraint="/.+@.+\.[a-z]+/"/>
 +
</source>
 +
 +
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:
 +
 +
<source lang="java">
 +
new Textbox().setContraint("/.+@.+\\.[a-z]+/");
 +
</source>
 +
 +
==== Flags ====
 +
{{versionSince| 9.6.0}}
 +
 +
To specify the flags to the regular expression, you could add the flags after the ending slash of the regular expression.
 +
 +
For example, If you want to enable case-insensitive matching, you could add the flag as below.
 +
<source lang="xml">
 +
<textbox constraint="/[A-Z]{3}/i"/>
 +
</source>
 +
 +
The flags supported:
 +
{| class='wikitable' | width="100%"
 +
! flags !! Description
 +
|-
 +
| i
 +
| ignore case
 +
|-
 +
| m
 +
| multiline
 +
|-
 +
| s
 +
| dotAll
 +
|-
 +
| u
 +
| unicode
 +
|}
 +
Notice: the regular expression will always use global match no matter if the <code>g</code> flag is added or not.
 +
 +
=== Multiple Constraints ===
 +
Notice that it is allowed to mix regular expression with other constraints by separating them with a comma.
 +
 +
If you prefer to display an application dependent message instead of the default one, you could append the constraint with a colon and the message you want to display when failed.
 +
 +
<source lang="xml">
 +
<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" />
 +
</source>
 +
 +
 +
=== i18n Error Message ===
 +
To support multilingual, you could use [[ZUML Reference/EL Expressions/Core Methods/l|the l function]] as depicted in [[ZK Developer's Reference/Internationalization|ZK Developer's Reference]].
 +
 +
<source lang="xml">
 +
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c"?>
 +
<textbox constraint="/.+@.+\.[a-z]+/: ${c:l('err.email.required')}"/>
 +
</source>
 +
 +
 +
=== Escape a Comma ===
 +
{{versionSince|8.0.0}}
 +
If you want to write a longer sentence with comma separator, you can enclose your customized sentence with curly braces.
 +
 +
<source lang="xml">
 +
<textbox constraint="no empty: {Sorry, no empty allowed}, /.+@.+\.[a-z]+/: email only"></textbox>
 +
</source>
 +
 +
=== Scrollable Error Messag ===
 +
If you want to move an error message box by scrolling, please use [http://books.zkoss.org/wiki/ZUML_Reference/ZUML/Namespaces/Client_Attribute/Data-Scrollable data-scrollable attribute].
  
 
==Custom Constraint==
 
==Custom Constraint==
Line 160: Line 207:
 
If you want a custom constraint, you could implement <javadoc type="interface">org.zkoss.zul.Constraint</javadoc> and specify it in the constraint property (<javadoc method="setConstraint(org.zkoss.zul.Constraint)">org.zkoss.zul.impl.InputElement</javadoc>).  
 
If you want a custom constraint, you could implement <javadoc type="interface">org.zkoss.zul.Constraint</javadoc> and specify it in the constraint property (<javadoc method="setConstraint(org.zkoss.zul.Constraint)">org.zkoss.zul.impl.InputElement</javadoc>).  
 
   
 
   
<source lang="java" high="5">
+
<source lang="java" highlight="4">
public class EventNumberConstraint implements Constraint {
+
public class EvenNumberConstraint implements Constraint {
public void validate(Component comp, Object value) throws WrongValueException {
+
    public void validate(Component comp, Object value) throws WrongValueException {
if (value != null && (value.intValue() & 1) != 0) //assume used with intbox
+
        if (value != null && new Integer(value.toString()).intValue() % 2 == 1)
throw new WrongValueException(comp, "Only even numbers are allowed, not "+value);
+
            throw new WrongValueException(comp, "Only even numbers are allowed, not "+value);
}
+
    }
 
}
 
}
 
</source>
 
</source>
 
+
* Line 4: If the validation fails, just throw <javadoc>org.zkoss.zk.ui.WrongValueException</javadoc>. Notice that you have to specify which component causes the exception.
If the validation fails, just throw <javadoc>org.zkoss.zk.ui.WrongValue</javadoc> to indicate it. Notice that you have to specify which component causes the exception as shown in line 5.
 
  
 
To specify it to the constraint property, you have to instantiate it first by use of [[ZUML Reference/EL Expressions/Core Methods/new|the new function]] as shown below
 
To specify it to the constraint property, you have to instantiate it first by use of [[ZUML Reference/EL Expressions/Core Methods/new|the new function]] as shown below
Line 175: Line 221:
 
<source lang="xml">
 
<source lang="xml">
 
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c"?>
 
<?taglib uri="http://www.zkoss.org/dsp/web/core" prefix="c"?>
<textbox constraint="${c:new('foo.EventNumberConstraint')}"/>
+
<textbox constraint="${c:new('foo.EvenNumberConstraint')}"/>
 
</source>
 
</source>
  
Line 211: Line 257:
  
 
===Validate at Client for Better Responsiveness===
 
===Validate at Client for Better Responsiveness===
Responsiveness could be improved by validating more constraints at the client side<ref>The default constraint (<javadoc>org.zkoss.zul.SimpleConstraint</javadoc>) validates all constraints at the client side</ref>. To do it, you have to implement <javadoc type="interface">org.zkoss.zul.ClientConstraint</javadoc> (with <javadoc type="interface">org.zkoss.zul.Constraint</javadoc>).
+
Responsiveness could be improved by validating more constraints at the client side<ref>The default constraint (<javadoc>org.zkoss.zul.SimpleConstraint</javadoc>) validates all constraints at the client side</ref>. To do that, you have to implement <javadoc type="interface">org.zkoss.zul.ClientConstraint</javadoc> (with <javadoc type="interface">org.zkoss.zul.Constraint</javadoc>).
  
 
<blockquote>
 
<blockquote>
Line 223: Line 269:
  
 
<source lang="java">
 
<source lang="java">
public class FooComposer extends SelectorComposer {
+
public class CustomValidationComposer extends SelectorComposer {
 
   @Wire
 
   @Wire
 
   private Textbox username;
 
   private Textbox username;
Line 232: Line 278:
 
   public void doLogin() {
 
   public void doLogin() {
 
     username.clearErrorMessage(); //important to clear the previous error, if any
 
     username.clearErrorMessage(); //important to clear the previous error, if any
     if (examine(username, password)) {
+
     if (validate(username, password)) {
 
       //success
 
       //success
 
     } else {
 
     } else {
Line 262: Line 308:
  
 
==Instant==
 
==Instant==
The feature is available since 6.0.0. When instant mode is on, the onChange event will be fired as soon as possible as user types in the input (like onChanging event). The value will also be updated to the component (server side) immediately.
+
{{versionSince| 6.0.0}}
 +
default: <code>false</code>
 +
 
 +
When the instant mode is on, the <code>onChange</code> event will be fired as soon as possible as a user is typing in the input (like <code>onChanging</code> event). The value will also be updated to the component (server-side) immediately.
 +
Notice that it would automatically synchronize the value (including format) in the client and server. If you want to do something in the server while changing the value, please use <code>onChanging</code> event.
  
 
==Placeholder==
 
==Placeholder==
since 6.5.0
+
{{versionSince| 6.5.0}}
 
ZK 6.5 introduces support for HTML5 placeholder text, a very useful feature for telling users what they should enter in a textbox. This is a widely regarded UI pattern.
 
ZK 6.5 introduces support for HTML5 placeholder text, a very useful feature for telling users what they should enter in a textbox. This is a widely regarded UI pattern.
  
Line 274: Line 324:
 
<source lang="xml">
 
<source lang="xml">
 
<textbox placeholder="Please type some text" />
 
<textbox placeholder="Please type some text" />
 +
</source>
 +
 +
==InputAttributes==
 +
{{versionSince| 8.6.1}}
 +
The feature is available since 8.6.1. All input elements can set some additional attributes to the input html tag in the component.
 +
The inputAttributes can take a Map with attribute names as the keys or a String separated by ";" and followed the name=value rule.
 +
 +
<source lang="xml">
 +
<bandbox inputAttributes="${map}"></bandbox>
 +
<datebox inputAttributes="autocorrect=off;spellcheck=ture"></datebox>
 
</source>
 
</source>
  
 
=Supported Events=
 
=Supported Events=
  
{| border="1" | width="100%"
+
{| class='wikitable' | width="100%"
 
! <center>Name</center>
 
! <center>Name</center>
 
! <center>Event Type</center>
 
! <center>Event Type</center>
 
|-
 
|-
| <center><tt>onChange</tt></center>
+
| <center><code>onChange</code></center>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.InputEvent</javadoc>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.InputEvent</javadoc>
 
Denotes the content of an input component has been modified by the user.
 
Denotes the content of an input component has been modified by the user.
 
|-
 
|-
| <center><tt>onChanging</tt></center>
+
| <center><code>onChanging</code></center>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.InputEvent</javadoc>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.InputEvent</javadoc>
Denotes that user is changing the content of an input component. Notice that the component's content (at the server) won't be changed until <tt>onChange</tt> is received. Thus, you have to invoke the <tt>getValue </tt>method in the <tt>InputEvent </tt>class to retrieve the temporary value.
+
Denotes that user is changing the content of an input component. Notice that the component's content (at the server) won't be changed until <code>onChange</code> is received. Thus, you have to invoke the <code>InputEvent.getValue()</code> to retrieve the changed value.
 
|-
 
|-
| <center><tt>onSelection</tt></center>
+
| <center><code>onSelection</code></center>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.SelectionEvent</javadoc>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.SelectionEvent</javadoc>
Denotes that user is selecting a portion of the text of an input component. You can retrieve the start and end position of the selected text by use of the <tt>getStart</tt> and <tt>getEnd</tt> methods.''' '''
+
Denotes that user is selecting a portion of the text of an input component. You can retrieve the start and end position of the selected text by use of the <code>getStart</code> and <code>getEnd</code> methods.''' '''
 
|-
 
|-
| <center><tt>onFocus</tt></center>
+
| <center><code>onFocus</code></center>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.Event</javadoc>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.Event</javadoc>
Denotes when a component gets the focus. Remember event listeners execute at the server, so the focus at the client might be changed when the event listener for <tt>onFocus</tt> got executed.
+
Denotes when a component gets the focus. Remember event listeners execute at the server, so the focus at the client might be changed when the event listener for <code>onFocus</code> is executed.
 
|-
 
|-
| <center><tt>onBlur</tt></center>
+
| <center><code>onBlur</code></center>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.Event</javadoc>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.Event</javadoc>
Denotes when a component loses the focus. Remember event listeners execute at the server, so the focus at the client might be changed when the event listener for <tt>onBlur </tt>got executed.
+
Denotes when a component loses the focus. Remember event listeners execute at the server, so the focus at the client might be already changed when executing the <code>onBlur</code> listener.
 
|-
 
|-
| <center><tt>onError</tt></center>
+
| <center><code>onError</code></center>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.ErrorEvent</javadoc>
 
| '''Event:''' <javadoc>org.zkoss.zk.ui.event.ErrorEvent</javadoc>
 
Denotes when a component caused a validation error.
 
Denotes when a component caused a validation error.
 
|}
 
|}
 +
 +
[[ZK_Component_Reference/Base_Components/XulElement#Supported_Events | Inherited Supported Events from XulElement]]
  
 
=Supported Children=
 
=Supported Children=
Line 313: Line 375:
 
=Use cases=
 
=Use cases=
  
{| border='1px' | width="100%"
+
{| class='wikitable' | width="100%"
 
! Version !! Description !! Example Location
 
! Version !! Description !! Example Location
 
|-
 
|-
Line 319: Line 381:
 
| &nbsp;
 
| &nbsp;
 
| &nbsp;
 
| &nbsp;
 +
|}
 +
 +
=Browser Limitations=
 +
 +
{| class='wikitable' | width="100%"
 +
! Browser !! description
 +
|-
 +
| iOS Safari / Chrome
 +
|
 +
<source lang="xml">
 +
<textbox id="test"/>
 +
<button label="java focus (no keyboard)" onClick="test.focus()"></button>
 +
<button xmlns:w="client" label="client focus" w:onClick="zk.Widget.$('$test').focus();"></button>
 +
</source>
 +
In mobile Safari, the user must explicitly tap the elements in the web view to display the keyboard.
 
|}
 
|}
  
 
=Version History=
 
=Version History=
  
{| border='1px' | width="100%"
+
{| class='wikitable' | width="100%"
 
! Version !! Date !! Content
 
! Version !! Date !! Content
 
|-
 
|-
Line 332: Line 409:
 
| 6.0.0
 
| 6.0.0
 
| Sep, 2011
 
| Sep, 2011
| Add instant mode, which sends onChange event and update value to component as soon as possible.
+
| Add instant mode, which sends onChange event and updates value to component as soon as possible.
 
|-
 
|-
 
| 6.5.0
 
| 6.5.0
 
| Sep, 2012
 
| Sep, 2012
 
| Support HTML5 placeholder attribute for input elements
 
| Support HTML5 placeholder attribute for input elements
 +
|-
 +
| 8.5.2
 +
| May, 2018
 +
| [http://tracker.zkoss.org/browse/ZK-3774 ZK-3774]: focus() doesn't work on mobile device
 +
|-
 +
| 8.6.1
 +
| Jan, 2019
 +
| [http://tracker.zkoss.org/browse/ZK-4111 ZK-4111]: Add autocorrect and spellcheck DOM attributes toggles to input-based components
 
|}
 
|}
  
 
{{ZKComponentReferencePageFooter}}
 
{{ZKComponentReferencePageFooter}}

Latest revision as of 08:14, 12 April 2024

Input Element

Employment/Purpose

InputElement is a super class for components which handle user key input, such as textbox, intbox, decimalbox, doublebox, datebox, timebox, spinner, combobox, and bandbox.

Some features are implemented in this class, such as constraint, disabled, maxlength, name, readonly, and so on.

You should not use this class directly, please use the inherited class.

Example

<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>

CrInputs.png

Validation

There are two ways to validate the value entered by a user: implementing Constraint or throwing WrongValueException.

Constraint

An input element can be associated with a constraint (Constraint) to validate the value entered by a user. There is a default implementation called SimpleConstraint that can handle many conditions. If it is not enough, you can implement your own constraint, or throw WrongValueException as described in the next sections.

Built-in Constraints

To use the default constraint, you could specify a list of conditions in InputElement.setConstraint(String), such as no positive and no empty. For example,

<textbox constraint="no empty"/>
<intbox constraint="no negative,no zero"/>


Condition Description
You can specify the following values at constraint attribute to apply them
no empty Empty is 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 Date only allowed between the specified range. The format must be yyyyMMdd, such as
<datebox constraint="between 20071225 and 20071203"/>
after yyyyMMdd Date only allowed after (and including) the specified date. The format must be yyyyMMdd, such as
<datebox constraint="after 20071225"/>
before yyyyMMdd Date only allowed before (and including) the specified date. The format must be yyyyMMdd, such as
<datebox constraint="before 20071225"/>
end_before
end_after
after_start
after_end
...
Specifies the position of the error box. Please refer to Popup for all allowed positions.
<textbox constraint="no empty, end_after"/>
<textbox constraint="no empty, start_before"/>


Regular Expression

To specify a regular expression, you could have to use / to enclose the regular expression as follows.

<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]+/");

Flags

Since 9.6.0

To specify the flags to the regular expression, you could add the flags after the ending slash of the regular expression.

For example, If you want to enable case-insensitive matching, you could add the flag as below.

<textbox constraint="/[A-Z]{3}/i"/>

The flags supported:

flags Description
i ignore case
m multiline
s dotAll
u unicode

Notice: the regular expression will always use global match no matter if the g flag is added or not.

Multiple Constraints

Notice that it is allowed to mix regular expression with other constraints by separating them with a comma.

If you prefer to display an application dependent message instead of the default one, you could append the constraint with a colon and the message you want to display when failed.

<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" />


i18n Error Message

To support multilingual, you could use the l function as depicted in ZK Developer's Reference.

<?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 If you want to write a longer sentence with comma separator, you can enclose your customized sentence with curly braces.

<textbox constraint="no empty: {Sorry, no empty allowed}, /.+@.+\.[a-z]+/: email only"></textbox>

Scrollable Error Messag

If you want to move an error message box by scrolling, please use data-scrollable attribute.

Custom Constraint

If you want a custom constraint, you could implement Constraint and specify it in the constraint property (InputElement.setConstraint(Constraint)).

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);
    }
}
  • Line 4: If the validation fails, just throw WrongValueException. Notice that you have to specify which component causes the exception.

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

Instead of the default error box, you could provide a custom approach by implementing CustomConstraint (with Constraint). Then, CustomConstraint.showCustomError(Component, WrongValueException) will be invoked when an exception is caught. For example,

<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

CrCustomConstraint.png

Validate at Client for Better Responsiveness

Responsiveness could be improved by validating more constraints at the client side[1]. To do that, you have to implement ClientConstraint (with Constraint).


  1. The default constraint (SimpleConstraint) validates all constraints at the client side

WrongValueException

In addition to throwing WrongValueException in Constraint.validate(Component, Object), you can throw WrongValueException in other situations. For example, you can validate the user name and password when the user presses the login button. For example,

public class CustomValidationComposer extends SelectorComposer {
  @Wire
  private Textbox username;
  @Wire
  private Textbox password;

  @Listen("onClick = #login")
  public void doLogin() {
    username.clearErrorMessage(); //important to clear the previous error, if any
    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

All input elements can have the in-place-editing functionality, like the combobox, textbox, datebox, and so on.

<grid width="500px">
	<rows>
		<row>
			Textbox:
			<textbox inplace="true" value="Click me" />
		</row>
		<row>
			Combobox:
			<combobox inplace="true" value="Click me" />
		</row>
	</rows>
</grid>

Instant

Since 6.0.0 default: false

When the instant mode is on, the onChange event will be fired as soon as possible as a user is typing in the input (like onChanging event). The value will also be updated to the component (server-side) immediately. Notice that it would automatically synchronize the value (including format) in the client and server. If you want to do something in the server while changing the value, please use onChanging event.

Placeholder

Since 6.5.0 ZK 6.5 introduces support for HTML5 placeholder text, a very useful feature for telling users what they should enter in a textbox. This is a widely regarded UI pattern.

The following image and code show the look of the placeholder as well as the code to replicate it.

Zk textbox placeholder.png

<textbox placeholder="Please type some text" />

InputAttributes

Since 8.6.1 The feature is available since 8.6.1. All input elements can set some additional attributes to the input html tag in the component. The inputAttributes can take a Map with attribute names as the keys or a String separated by ";" and followed the name=value rule.

<bandbox inputAttributes="${map}"></bandbox>
<datebox inputAttributes="autocorrect=off;spellcheck=ture"></datebox>

Supported Events

Name
Event Type
onChange
Event: InputEvent

Denotes the content of an input component has been modified by the user.

onChanging
Event: InputEvent

Denotes that user is changing the content of an input component. Notice that the component's content (at the server) won't be changed until onChange is received. Thus, you have to invoke the InputEvent.getValue() to retrieve the changed value.

onSelection
Event: SelectionEvent

Denotes that user is selecting a portion of the text of an input component. You can retrieve the start and end position of the selected text by use of the getStart and getEnd methods.

onFocus
Event: Event

Denotes when a component gets the focus. Remember event listeners execute at the server, so the focus at the client might be changed when the event listener for onFocus is executed.

onBlur
Event: Event

Denotes when a component loses the focus. Remember event listeners execute at the server, so the focus at the client might be already changed when executing the onBlur listener.

onError
Event: ErrorEvent

Denotes when a component caused a validation error.

Inherited Supported Events from XulElement

Supported Children

*None

Use cases

Version Description Example Location
     

Browser Limitations

Browser description
iOS Safari / Chrome
<textbox id="test"/>
<button label="java focus (no keyboard)" onClick="test.focus()"></button>
<button xmlns:w="client" label="client focus" w:onClick="zk.Widget.$('$test').focus();"></button>

In mobile Safari, the user must explicitly tap the elements in the web view to display the keyboard.

Version History

Version Date Content
5.0.8 June, 2011 Allow user to specify the position of error-box
6.0.0 Sep, 2011 Add instant mode, which sends onChange event and updates value to component as soon as possible.
6.5.0 Sep, 2012 Support HTML5 placeholder attribute for input elements
8.5.2 May, 2018 ZK-3774: focus() doesn't work on mobile device
8.6.1 Jan, 2019 ZK-4111: Add autocorrect and spellcheck DOM attributes toggles to input-based components



Last Update : 2024/04/12

Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.