Form required fields

trigirl67

Registered User.
Local time
Today, 12:31
Joined
Dec 10, 2011
Messages
10
How do you make certain fields "required" to be completed before exiting?
 
The advantage to Paul's method, from the link he gave, using validation code in the Form_BeforeUpdate event, is that you can pop up a message to the user that makes sense to the user! The Access-generated error messages that pop up when you attempt to leave a Record with Required Fields unpopulated can be very, very cryptic.

Paul gave you an example with a single Control that needed filling, if you have multiple Controls to validate, you'll need to add one more line per Control:

Exit Sub

Otherwise the code will continue to drop thru the first validation directly to the second validation, not allowing the user the opportunity to correct the first omission:
Code:
Private Sub Form_BeforeUpdate(Cancel As Integer)

If  Len(Me.Control1 & vbNullString) = 0
   MsgBox "Control1 Must Not Be Left Blank!"
   Cancel = True
   Control1.SetFocus
   Exit Sub
 End If
 
 If Len(Me.Control2 & vbNullString) = 0
   MsgBox "Control2 Must Not Be Left Blank!"
   Cancel = True
   Control2.SetFocus
   Exit Sub
 End If

End Sub

If you have a slew of Controls that are required, post back, and we can show you how to mark all Controls that are required and then loop through them to do the validation.

Linq ;0)>
 
Last edited:
It may also be a good idea to give a visual clue to the users, like having all mandatory field with a different background colour or an asterisk * after the name in the label, so they can see what information is required before they start adding data.

You could apply a naming convention to your controls on the form as well which could be useful.

txtTextBoxName_mn

Then you could write a function to run through the controls to check for data.

(The following code is off the top of my head without being checked)

Code:
Private Function missingData() AS Integer
Dim ctl as Control

missingData = False

For Each ctl in Me.Controls

  if right(ctl.name,3) = "_mn" Then

    If len(ctl.Text & vbNullString) = 0 Then

      missingData = True
      ctl.setFocus
      MsgBox "Control '" & ctl.Name & "' should contain a value", vbCritical + vbOkOnly
      Exit Function

    End If

  End If

Next ctl

End Function

Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = missingData()
End Sub
 
Last edited:

Users who are viewing this thread

Back
Top Bottom