Question : Check validity before record is saved or edited on a form

Hi Guys,

This is a rather general question. I have a form which is bound to records in my table. For each record that user wants to add/edit, I want to make sure certain fields are not empty before the record is saved into my table. And I also don't want any duplicates in my table. I know the logic is pretty simple, but where shall I put in my code?

Can anyone direct me to the right track about this?
Many thanks.

Answer : Check validity before record is saved or edited on a form

You can also setup Unique Indexes on the table, with those fields as Required. This has the similar effect of what Gary described.

However, from a UI perspective, you could use the BeforeUpdate event of your form to check those fields and insure they're filled in. The Required property or index method can throw some pretty odd (and hard to understand) errors, while you can build much more user-friendly errors using the BeforeUpdate method. BeforeUpdate fires before the data is written to the table, so it's useful for both new and existing records:

Sub Form_BeforeUpdate(Cancel As Integer)
  Dim sError As String
  If Nz(Me.txCustomerName, "") = "" Then
    sError = "You must enter a company name"
  End If

  If Nz(me.txCustomerPhone, "") = "" Then
    If Len(sError) > 0 Then sError = sError & vbCrLf
    sError = sError & "You must enter a Company Phone number"
  End If
 
  If Len(sError)> 0 Then
    Msgbox "You must fill in all required fields: " & vbCrLf & sError, vbOkOnly + vbExclamation, "Missing or Invalid Data"
    Cancel = True
  End If
End Sub

Note the "Cancel = True" - this is what tells Access to NOT save the data as is. Users must either (a) fill in the data or (b) use the Esc key to cancel out of the form (which discards all changes/inserts).

Note you can also use the BeforeUpdate event of your controls to do the same thing. In many cases this is preferred since you sometimes must have ControlA filled in before you can select/enter something in ControlB.
Random Solutions  
 
programming4us programming4us