WklValidator
WklValidator class
Signature
Dim myWklValidator As WklValidator Set myWklValidator = Me!ControlName.Object
Summary
Checks the controls of the Access form it sits on: rules per control or field, shown at the text box and in the summary the control draws, and the save of a record refused while a rule is broken.
Parameters
None
Remarks
Put one validator on the form that edits the records - for example the edit form of a WklGrid or WklTreeList (EditForm) - and give it its rules in Rules. The form needs a module: set Has Module (HasModule) to Yes; an empty module is enough. Access raises a form's events to a control only when the form has a module (a form without module raises none, also with [Event Procedure] in its event properties). The validator sets the event properties it needs - Before Update, After Update, On Error, On Current, and On Undo of the form, and Before Update of the checked controls - to [Event Procedure] itself when they are empty; a property that holds a macro or an expression is left alone, and its event goes there instead. Without a module the summary says that the check is inactive, and IsConnected is False.
When it checks:
- A field when the user leaves it (
ValidateModewvmOnLeave, default): a broken rule keeps the focus in the field, as an Access validation rule does - but without its message box. - While the user types, as a mark only (
wvmImmediate); leaving the field is refused as withwvmOnLeave. - The whole record before it is saved, in every mode: every field rule, the record rules and the event
ValidateRecord. A broken rule refuses the save. This includes the save Access makes when the focus goes from a docked edit form back to the list (also with the edit form two subform levels deep): the record stays as it is, the focus stays in the edit form, and the summary shows why.
What it shows: the border of the text box in red (a transparent border becomes solid while marked) and the message as its ControlTipText, both restored when the error goes; in its own rectangle, the summary „2 Fehler – first message“ on the colors of a „bad“ status, empty without errors. A click on the summary, Enter or a screen reader's Invoke goes to the first error. The summary is a live region: screen readers read a new error without the focus leaving the field. Errors of the data source on saving (a validation rule of the table, a data service that refuses the record through its ODBC driver) appear in the summary too (HandleDataErrors). A new record, a saved one and Undo clear all errors.
The validator works on Access forms only. In design view it shows its name and the number of rules. Like every WKL control it cannot be created with CreateControl; a build script inserts it as a control block (see How to: Put WKL controls into forms by code).
An ActiveX control: inserted into a form in design view (Form Design › Controls › ActiveX Controls); reports are not supported. VBA reaches it through the Object property of the control, where ControlName is the name of the control on the form.
| Member | Kind | Summary |
|---|---|---|
| `Rules` | Property | Gets or sets the rules as JSON text. |
| `ValidateMode` | Property | Gets or sets when a field is checked. |
| `HandleDataErrors` | Property | Gets or sets whether errors of the data source on saving appear in the summary instead of Access's message box. |
| `ErrorCount` | Property | Gets the number of errors shown. |
| `ErrorSummary` | Property | Gets the summary of the errors. |
| `ErrorText` | Property | Gets the message of a control or field, or of the record. |
| `SetError` | Method | Shows an error of the application. |
| `ClearErrors` | Method | Removes every error and restores the border and tooltip of the marked controls. |
| `GoToFirstError` | Method | Moves the focus to the control of the first error. |
| `Validate` | Method | Checks every rule for the current record and shows the errors. |
| `IsConnected` | Property | Gets whether the validator receives the events of its form. |
| Event | Summary |
|---|---|
| `ValidationChange` | Occurs when the errors shown have changed. |
| `ValidateRecord` | Occurs before the record is saved, after the rules have been checked. |
Code example
' Design view of the edit form frmIdentity, which has an empty module:
' Login only lower case letters, required for a login; exactly one of person, account and key.
Forms!frmIdentity!Validator1.Object.Rules = _
"{""fields"":[" & _
"{""field"":""Login"",""pattern"":""[a-z]+"",""text"":""Login nur aus Kleinbuchstaben""}," & _
"{""field"":""Login"",""required"":true,""when"":{""field"":""Kind"",""equals"":""Login""}}]," & _
"""records"":[{""exactlyOne"":[""PersonId"",""Account"",""KeyId""]}]}"
Inheritance
None
Rules property
Signature
Property Get Rules() As String Property Let Rules(RHS As String)
Summary
Gets or sets the rules as JSON text.
Parameters
None
Property value: String – {"fields":[...],"records":[...]}; empty (default) for none.
Remarks
A field rule names field and any of required (true), maxLength (characters), pattern (a .NET regular expression the whole text must match), min and max (a number, or a date as ISO text such as "2026-01-31", or a text), valueList (an Access value list such as "a;b;c"), text (the message instead of the generated one) and when ({"field":"Item","in":["from","except_from"]} or {"field":"Kind","equals":"Login"}: the rule applies only while that field holds one of the values). A field may have several rules, one per condition; the first that applies and fails names the error. A record rule names its kind - exactlyOne, atLeastOne or atMostOne - with at least two fields, and optionally text and when.
How a field is found. field - like when.field and the fields of a record rule - is first the name of a control of the form, else the field of the record source that a control shows: the control whose Control Source is exactly that field (a calculated control, =expression, never counts). A field without such a control is read from the record (Me("Field")); it is checked before saving, but nothing can be marked. With a text box txtName bound to Name, "txtName" and "Name" find the same control.
The name in messages is the caption of the control's attached label, without & and a trailing colon; without an attached label, the field as named in the rule. A label placed freely next to the control does not count - create the caption as the control's attached label.
Patterns are .NET regular expressions and always match the whole text: the validator puts ^(?: and )$ around them, so ^ and $ are not needed. Unicode classes work (\\p{L} for any letter; a backslash is written twice in JSON). A pattern that takes longer than a quarter of a second on one value counts as not matched.
An empty value is valid unless required is set: length, pattern, range and list check what was entered. Setting an invalid text raises wkeInvalidValue with what is wrong, for example a pattern that is no regular expression. Unknown properties are ignored, so a form saved by a newer version still opens. The value is saved with the form.
Read/write.
Code example
' A network for from/except_from, a data source name for database:
Me!Validator1.Object.Rules = "{""fields"":[" & _
"{""field"":""Value"",""pattern"":""(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}/(3[0-2]|[12]?\d)"",""when"":{""field"":""Item"",""in"":[""from"",""except_from""]}}," & _
"{""field"":""Value"",""pattern"":""[A-Za-z_][A-Za-z0-9_]*"",""when"":{""field"":""Item"",""equals"":""database""}}]}"
Inheritance
Declared by WklValidator.
ValidateMode property
Signature
Property Get ValidateMode() As WklValidateMode Property Let ValidateMode(RHS As WklValidateMode)
Summary
Gets or sets when a field is checked.
Parameters
None
Property value: `WklValidateMode` – A WklValidateMode value; wvmOnLeave (default).
Remarks
The record is checked before it is saved in every mode. The value is saved with the form.
Read/write.
Code example
None
Inheritance
Declared by WklValidator.
HandleDataErrors property
Signature
Property Get HandleDataErrors() As Boolean Property Let HandleDataErrors(RHS As Boolean)
Summary
Gets or sets whether errors of the data source on saving appear in the summary instead of Access's message box.
Parameters
None
Property value: Boolean – True (default) or False.
Remarks
With True the validator answers the form's Error event with acDataErrContinue and shows the text in the summary: for an ODBC error the reasons of the driver from DBEngine.Errors (a data service's refusal), otherwise Access's text of the error. The record stays unsaved and the focus where it was.
The path applies only to a save Access makes during a user action (moving to another record, closing the form, clicking from a docked edit form into its list). A save started by code reports its error to that code instead and raises no Error event, as in every Access form: Me.Dirty = False, RunCommand acCmdSaveRecord, and also moving the focus by code (area!grdMain.SetFocus), whose save belongs to that code. With a validation rule of the table (3316) or a data service refusing the record through its ODBC driver (3155), the record stays unsaved, the error reaches the code, and the summary stays empty. Catch the error there and pass the text to SetError. The trace of the controls shows Validator: Error received when Access raised the event (see A refused save does not show in the validator's summary). The value is saved with the form.
Read/write.
Code example
Private Sub cmdSpeichern_Click()
On Error GoTo Abgelehnt
Me.Dirty = False
Exit Sub
Abgelehnt:
Me!Validator1.Object.SetError "", Err.Description
End Sub
Inheritance
Declared by WklValidator.
ErrorCount property
Signature
Property Get ErrorCount() As Long
Summary
Gets the number of errors shown.
Parameters
None
Property value: Long – The errors of fields and of the record; 0 without errors.
Remarks
Read-only.
Code example
None
Inheritance
Declared by WklValidator.
ErrorSummary property
Signature
Property Get ErrorSummary() As String
Summary
Gets the summary of the errors.
Parameters
None
Property value: String – „1 Fehler“, „2 Fehler“ …; empty without errors.
Remarks
Read-only.
Code example
None
Inheritance
Declared by WklValidator.
ErrorText property
Signature
Property Get ErrorText(ByVal Control As String) As String
Summary
Gets the message of a control or field, or of the record.
Parameters
| Name | Type | Optional | Default | Description |
|---|---|---|---|---|
Control | String | No | – | A control's name or a field; empty for the error of the record. |
Property value: String – The message; empty without error.
Remarks
Read-only.
Code example
None
Inheritance
Declared by WklValidator.
SetError method
Signature
Sub SetError(ByVal Control As String, ByVal Text As String)
Summary
Shows an error of the application.
Parameters
| Name | Type | Optional | Default | Description |
|---|---|---|---|---|
Control | String | No | – | A control's name or a field: the control is marked; empty: the error appears in the summary only. |
Text | String | No | – | The message; empty to remove the error. |
Remarks
For rules the validator cannot express, and for refusals of a data service that names no field. An error of the application stays until it is removed, the record changes or ClearErrors is called; it also refuses the save while it names a control.
Code example
Me!Validator1.Object.SetError "Login", "Dieser Login ist schon vergeben."
Inheritance
Declared by WklValidator.
ClearErrors method
Signature
Sub ClearErrors()
Summary
Removes every error and restores the border and tooltip of the marked controls.
Parameters
None
Remarks
None
Code example
None
Inheritance
Declared by WklValidator.
GoToFirstError method
Signature
Sub GoToFirstError()
Summary
Moves the focus to the control of the first error.
Parameters
None
Remarks
Raises wkeNotAvailable without errors. An error of the record has no control; the focus then goes to the first field with an error, if there is one.
Code example
None
Inheritance
Declared by WklValidator.
Validate method
Signature
Function Validate() As Boolean
Summary
Checks every rule for the current record and shows the errors.
Parameters
None
Return value: Boolean
Remarks
For a button of your own that should check before it acts. It also works when the form has no module (only the automatic checks need one).
Code example
Private Sub cmdWeiter_Click()
If Me!Validator1.Object.Validate Then DoCmd.GoToRecord , , acNext
End Sub
Inheritance
Declared by WklValidator.
IsConnected property
Signature
Property Get IsConnected() As Boolean
Summary
Gets whether the validator receives the events of its form.
Parameters
None
Property value: Boolean – True in form view on a form with a module; False in design view, on a form without module, and outside Access.
Remarks
Read-only.
Code example
None
Inheritance
Declared by WklValidator.
ValidationChange event
Signature
Event ValidationChange()
Summary
Occurs when the errors shown have changed.
Parameters
None
Remarks
Read ErrorCount and ErrorSummary for your own display. Like all events of the control it needs a procedure in the form's module.
In a form module: Private Sub <ControlName>_ValidationChange(...). Parameters passed by reference can be changed by the procedure.
Code example
None
Inheritance
Declared by WklValidator.
ValidateRecord event
Signature
Event ValidateRecord(ByRef Message As String, ByRef Cancel As Integer)
Summary
Occurs before the record is saved, after the rules have been checked.
Parameters
| Name | Type | Optional | Default | Description |
|---|---|---|---|---|
Message | String (by reference) | No | – | Set it to the reason when the record must not be saved. |
Cancel | Integer (by reference) | No | – | Set to True to refuse the save. |
Remarks
For a record rule the rules cannot express. A refusal without message shows „Der Datensatz wurde abgelehnt.“
In a form module: Private Sub <ControlName>_ValidateRecord(...). Parameters passed by reference can be changed by the procedure.
Code example
Private Sub Validator1_ValidateRecord(Message As String, Cancel As Integer)
If Me!Kind = "Login" And DCount("*", "tblIdentity", "Login = '" & Me!Login & "' AND Id <> " & Nz(Me!Id, 0)) > 0 Then
Message = "Dieser Login ist schon vergeben."
Cancel = True
End If
End Sub
Inheritance
Declared by WklValidator.