473,396 Members | 2,011 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Form validation; I've been doing it wrong so now time to learn how properly

374 256MB
Hi all,

Basically I have been using form validation incorrectly. Partly because of laziness which I now feel is going to really bite me back if I dont get it sorted.

On all of my forms I have a save button. Simply because it is often easier to explain to people just click save and it will save the record than it is for them to grasp the idea that access doesnt need a record to be "saved" from a button.

In the click event of this save button I carry out form validation.

Here is some sample code:

Expand|Select|Wrap|Line Numbers
  1. Private Sub Command228_Click()
  2. Dim errorstring As String
  3.  
  4. On Error GoTo FightingSomethingBeatable
  5.  
  6.  
  7. If Len(Nz(Me.subfrmInvestigation_tools.Form.InvStartDate)) < 1 Then
  8.     Me.subfrmInvestigation_tools.Form.InvStartDate.SetFocus
  9.     Me.subfrmInvestigation_tools.Form.InvStartDate.BackColor = vbRed
  10.     errorstring = errorstring & "The investigation start date must be entered." & vbCrLf
  11. Else
  12.     Me.subfrmInvestigation_tools.Form.InvStartDate.BackColor = 16579561
  13. End If
  14.  
  15. If Len(Nz(Me.subfrmInvestigation_tools.Form.InvEndDate)) < 1 Or (Me.subfrmInvestigation_tools.Form.InvEndDate - Me.subfrmInvestigation_tools.Form.InvStartDate) < 0 Then
  16.     Me.subfrmInvestigation_tools.Form.InvEndDate.SetFocus
  17.     Me.subfrmInvestigation_tools.Form.InvEndDate.BackColor = vbRed
  18.     errorstring = errorstring & "The investigation end date must be entered." & vbCrLf
  19. Else
  20.     Me.subfrmInvestigation_tools.Form.InvEndDate.BackColor = 16579561
  21. End If
  22.  
  23.  
  24. If Len(Nz(Me.subfrmInvestigation_tools.Form.InvTechandOutcome)) < 3 Then
  25.     Me.subfrmInvestigation_tools.Form.InvTechandOutcome.SetFocus
  26.     Me.subfrmInvestigation_tools.Form.InvTechandOutcome.BackColor = vbRed
  27.     errorstring = errorstring & "Information regarding the investigation must be added." & vbCrLf
  28. Else
  29.     Me.subfrmInvestigation_tools.Form.InvTechandOutcome.BackColor = 16579561
  30. End If
  31.  
  32.  
  33. If Me.Controls("subrootcauseform").Form.Recordset.RecordCount < 1 Then
  34.     Me.Controls("subrootcauseform").Form.RootCauseType.SetFocus
  35.     Me.Controls("subrootcauseform").Form.RootCauseType.BackColor = vbRed
  36.     Me.Controls("subrootcauseform").Form.RootCauseDescrip.BackColor = vbRed
  37.     errorstring = errorstring & "You must assign atleast one root cause for the nonconformance event." & vbCrLf
  38. Else
  39.     Me.Controls("subrootcauseform").Form.RootCauseType.BackColor = 16579561
  40.     Me.Controls("subrootcauseform").Form.RootCauseDescrip.BackColor = 16579561
  41. End If
  42.  
  43. If Me.Outcome = "Use as is" Or Me.Outcome = "Corrective action required" Then
  44.     Me.Outcome.BackColor = 16579561
  45. Else
  46.     Me.Outcome.SetFocus
  47.     Me.Outcome.BackColor = vbRed
  48.     errorstring = errorstring & "A valid outcome must be selected before an investigation can be completed." & vbCrLf
  49. End If
  50.  
  51. If Len(Nz(Me.txtoutcomedescrip)) < 3 Then
  52.     Me.txtoutcomedescrip.SetFocus
  53.     Me.txtoutcomedescrip.BackColor = vbRed
  54.     errorstring = errorstring & "A reasoning regarding the outcome must be present before an investigation can be completed." & vbCrLf
  55. Else
  56.     Me.txtoutcomedescrip.BackColor = 16579561
  57. End If
  58.  
  59. If Len(Nz(Me.txtoutcomeapprovedby)) < 2 Then
  60.     Me.txtoutcomeapprovedby.SetFocus
  61.     Me.txtoutcomeapprovedby.BackColor = vbRed
  62.     errorstring = errorstring & "The investigation outcome must be approved before an investigation can be completed." & vbCrLf
  63. Else
  64.     Me.txtoutcomeapprovedby.BackColor = 16579561
  65. End If
  66.  
  67. If Len(Nz(errorstring)) > 0 Then
  68. MsgBox errorstring, vbInformation, "Error in completion of investigation stage."
  69. Exit Sub
  70. Else
  71.  
  72. Select Case Me.Outcome
  73.  
  74.         Case "Use as is"
  75.             Me.Outcome.BackColor = 16579561
  76.             MsgBox "You have selected: Use as is." & vbCrLf & _
  77.             "The nonconformance will now be marked as ready for closure, no further action is required."
  78.             Me.NCStatus = 4
  79.             DoCmd.RunCommand acCmdSaveRecord
  80.  
  81.  
  82.         Case "Corrective action required"
  83.             Me.Outcome.BackColor = 16579561
  84.             MsgBox "You have selected: Corrective action required." & vbCrLf & _
  85.             "This status has been saved and corrective action(s) should now be assigned/recorded."
  86.             Me.NCStatus = 3
  87.             DoCmd.RunCommand acCmdSaveRecord
  88.  
  89.         Case Else
  90.  
  91.             If Me.Outcome <> "Use as is" Or Me.Outcome <> "Corrective action required" Then
  92.                 Me.Outcome.SetFocus
  93.                 Me.Outcome.BackColor = vbRed
  94.                 MsgBox ("Please select a valid outcome for the nonconformance event." & vbCrLf & _
  95.                 "Use as is - To continue using the subject without performing corrections." & vbCrLf & _
  96.                 "Corrective action required - Corrections required in order for the nonconformance to be closed.")
  97.                 Me.NCStatus = 3
  98.             Else
  99.                 Exit Sub
  100.             End If
  101.  
  102.     End Select
  103.  
  104. End If
  105.  
  106.  
  107. InchByInch:
  108.  
  109. Exit Sub
  110.  
  111. FightingSomethingBeatable:
  112. MsgBox Err.Description
  113. Resume InchByInch
  114.  
  115. End Sub

Now I know I SHOULD be using the Before_Update event of a form to do validation but for the life of me I can not find a simple example to follow.

I have found using my current method if validation fails and the user is required to fill in a section, they can still choose not to and move to a new record. They can also close the form and changes have already been commited to the database. I know I need to get cancel=true working which once again means before_update event. I have given this a go on a form producing the following:

Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_BeforeUpdate(Cancel As Integer)
  2. On Error GoTo Err_btnsavecorrective_Click
  3.  
  4. Dim ErrorStrings
  5.  
  6. 'Create the error form validation stuff here
  7.  
  8. ErrorStrings = vbNullString
  9.  
  10. If Len(Nz(Me.CorrectivePersonCarryout)) < 1 Then
  11.     Me.CorrectivePersonCarryout.SetFocus
  12.     Me.CorrectivePersonCarryout.BackColor = vbRed
  13.     ErrorStrings = ErrorStrings & "You must enter the name of the person who will be carrying out the action." & vbCrLf
  14.  
  15. Else
  16.  
  17.     Me.CorrectivePersonCarryout.BackColor = 16579561
  18.  
  19. End If
  20.  
  21. If Len(Nz(Me.CorrectiveDate)) < 1 Then
  22.     ErrorStrings = ErrorStrings & "You must enter a proposed date for the action to start." & vbCrLf
  23.     Me.CorrectiveDate.SetFocus
  24.     Me.CorrectiveDate.BackColor = vbRed
  25.  
  26. Else
  27.  
  28.     Me.CorrectiveDate.BackColor = 16579561
  29.  
  30. End If
  31.  
  32. If Len(Nz(Me.CorrectiveCompletedDate)) < 1 Or (Me.CorrectiveDate > Me.CorrectiveCompletedDate) Then
  33.     ErrorStrings = ErrorStrings & "You must enter a proposed date for the action to be completed." & vbCrLf
  34.     Me.CorrectiveCompletedDate.SetFocus
  35.     Me.CorrectiveCompletedDate.BackColor = vbRed
  36.  
  37. Else
  38.  
  39.     Me.CorrectiveCompletedDate.BackColor = 16579561
  40.  
  41. End If
  42.  
  43.  
  44.  
  45.  
  46. If Len(Nz(Me.CorrectiveDescription)) < 4 Then
  47.  
  48.     Me.CorrectiveDescription.SetFocus
  49.     Me.CorrectiveDescription.BackColor = vbRed
  50.     ErrorStrings = ErrorStrings & "You must supply an adequate description for the action." & vbCrLf
  51.  
  52. Else
  53.  
  54.     Me.CorrectiveDescription.BackColor = 16579561
  55.  
  56. End If
  57.  
  58.  
  59. 'Create the if statement to see if anything has been done incorrectly before allowing continuation
  60.  
  61. If Len(Nz(ErrorStrings)) > 0 Then
  62.  
  63. 'error has occured cancel any save of the record
  64. Cancel = True
  65.     MsgBox ErrorStrings, vbInformation, "Errors in your entries"
  66.  
  67.  
  68.  
  69. Exit Sub
  70. Else
  71.  
  72. 'everything looks to be ok allow the code to continue running
  73.  
  74. End If
  75. End Sub
With my save button having:
Expand|Select|Wrap|Line Numbers
  1. Private Sub btnsavecorrective_Click()
  2.  
  3.     DoCmd.RunCommand acCmdSaveRecord
  4.  
  5.  
  6.  
  7. Exit_btnsavecorrective_Click:
  8.     Exit Sub
  9.  
  10. Err_btnsavecorrective_Click:
  11.     MsgBox Err.Description
  12.     Resume Exit_btnsavecorrective_Click
  13.  
  14. End Sub
And to ensure I know the record has been commited:

Expand|Select|Wrap|Line Numbers
  1. Private Sub Form_AfterUpdate()
  2. MsgBox "Action saved.", vbInformation, "Success"
  3. End Sub
However for some reason the validation just isn't firing. this is what currently happens:

Load a new record in the sub form and click save = nothing happens = correct since nothing dirty

Load a new record and edit 1 field and click save = record saves and message box pops up to inform it has saved. = incorrect where is the form validation on the other fields?

Load a new record edit 1 field and click to move to next/previous record = record saves = correct but not what I want to happen I want the user to either select to save the changes or to cancel the changes and continue on.


Hopefully someone can help me out here as I know it is a fundamental problem in my designs and something which I want to ensure I get right.

Thanks for the help,

Chris
Aug 13 '10 #1

✓ answered by munkee

Got this all solved now. The basic framework should look like this:

Expand|Select|Wrap|Line Numbers
  1. Framework for saving records:
  2.  
  3. Private Sub Form_BeforeUpdate(Cancel As Integer)
  4. Dim ErrorStrings As String
  5.  
  6.  
  7.  
  8. 'The error string can be set to null for this first run
  9. ErrorStrings = vbNullString
  10.  
  11.  
  12. 'If the user tries to move off the record or any other event fires a save lets ask whether they actually want to do something with the changes or discard them
  13. If MsgBox("Changes have been made to this record." _
  14.         & vbCrLf & vbCrLf & "Do you want to save these changes?" _
  15.         , vbYesNo, "Changes Made...") = vbYes Then
  16.  
  17. 'Carry out the form validation to ensure everything is filled in correctly if it isnt lets get this stuff fixed and not save the current record
  18.  
  19.  
  20. If Len(Nz(Me.CorrectivePersonCarryout)) < 1 Then
  21.     Me.CorrectivePersonCarryout.SetFocus
  22.     Me.CorrectivePersonCarryout.BackColor = vbRed
  23.     Cancel = True
  24.     ErrorStrings = ErrorStrings & "You must enter the name of the person who will be carrying out the action." & vbCrLf
  25.  
  26. Else
  27.  
  28.     Me.CorrectivePersonCarryout.BackColor = 16579561
  29.  
  30. End If
  31.  
  32.  
  33.  
  34.  
  35. 'Create the if statement to see if anything has been done incorrectly before allowing continuation
  36.  
  37. If Len(Nz(ErrorStrings)) > 0 Then
  38.  
  39. 'error has occured cancel any save of the record
  40.  
  41.     MsgBox ErrorStrings, vbInformation, "Errors in your entries"
  42.  
  43. Cancel = True
  44. Exit Sub
  45. Else
  46. 'everything looks to be ok allow the code to continue running
  47. MsgBox "Action saved.", vbInformation, "Success"
  48.  
  49. End If
  50.  
  51. Else
  52.           DoCmd.RunCommand acCmdUndo
  53. 'Clear out any of the vbred backgrounds if an undo is selected 
  54. 'Me.CorrectiveDate.BackColor = 16579561
  55.  
  56.  
  57.  
  58.     End If
  59. End Sub
  60.  
  61.  
  62. '==================== Save button event
  63. Private Sub btnsavecorrective_Click()
  64. On Error GoTo Err_btnsavecorrective_Click
  65.  
  66.  
  67.     DoCmd.RunCommand acCmdSaveRecord
  68.  
  69.  
  70.  
  71. Exit_btnsavecorrective_Click:
  72.     Exit Sub
  73.  
  74. Err_btnsavecorrective_Click:
  75.  
  76. 'capture the correct error number and just change it.
  77. If Err = 2501 Then 'The command save record has been cancelled
  78. MsgBox "Save cancelled.", vbInformation, "Info"
  79.  
  80. Else
  81.     MsgBox Err.Description
  82.     Resume Exit_btnsavecorrective_Click
  83. End If
  84. End Sub
  85.  

2 1624
munkee
374 256MB
I have got the before update event to fire. It now validates as my save button would.

However my issue now is how would I incorporate my save buttons in to all of this. The problem I now have is that I wont be able to cancel the actual running of the save event. E.g.

Click save button to save the record. (Docmd.Runcommand accmdsaverecord)
Record runs through before update
Record fails validation and cancel = true fires
Click event can not save the record as intended therefore I get runtime error 2501 runcommand action was cancelled and a spew out in to vba.
Aug 13 '10 #2
munkee
374 256MB
Got this all solved now. The basic framework should look like this:

Expand|Select|Wrap|Line Numbers
  1. Framework for saving records:
  2.  
  3. Private Sub Form_BeforeUpdate(Cancel As Integer)
  4. Dim ErrorStrings As String
  5.  
  6.  
  7.  
  8. 'The error string can be set to null for this first run
  9. ErrorStrings = vbNullString
  10.  
  11.  
  12. 'If the user tries to move off the record or any other event fires a save lets ask whether they actually want to do something with the changes or discard them
  13. If MsgBox("Changes have been made to this record." _
  14.         & vbCrLf & vbCrLf & "Do you want to save these changes?" _
  15.         , vbYesNo, "Changes Made...") = vbYes Then
  16.  
  17. 'Carry out the form validation to ensure everything is filled in correctly if it isnt lets get this stuff fixed and not save the current record
  18.  
  19.  
  20. If Len(Nz(Me.CorrectivePersonCarryout)) < 1 Then
  21.     Me.CorrectivePersonCarryout.SetFocus
  22.     Me.CorrectivePersonCarryout.BackColor = vbRed
  23.     Cancel = True
  24.     ErrorStrings = ErrorStrings & "You must enter the name of the person who will be carrying out the action." & vbCrLf
  25.  
  26. Else
  27.  
  28.     Me.CorrectivePersonCarryout.BackColor = 16579561
  29.  
  30. End If
  31.  
  32.  
  33.  
  34.  
  35. 'Create the if statement to see if anything has been done incorrectly before allowing continuation
  36.  
  37. If Len(Nz(ErrorStrings)) > 0 Then
  38.  
  39. 'error has occured cancel any save of the record
  40.  
  41.     MsgBox ErrorStrings, vbInformation, "Errors in your entries"
  42.  
  43. Cancel = True
  44. Exit Sub
  45. Else
  46. 'everything looks to be ok allow the code to continue running
  47. MsgBox "Action saved.", vbInformation, "Success"
  48.  
  49. End If
  50.  
  51. Else
  52.           DoCmd.RunCommand acCmdUndo
  53. 'Clear out any of the vbred backgrounds if an undo is selected 
  54. 'Me.CorrectiveDate.BackColor = 16579561
  55.  
  56.  
  57.  
  58.     End If
  59. End Sub
  60.  
  61.  
  62. '==================== Save button event
  63. Private Sub btnsavecorrective_Click()
  64. On Error GoTo Err_btnsavecorrective_Click
  65.  
  66.  
  67.     DoCmd.RunCommand acCmdSaveRecord
  68.  
  69.  
  70.  
  71. Exit_btnsavecorrective_Click:
  72.     Exit Sub
  73.  
  74. Err_btnsavecorrective_Click:
  75.  
  76. 'capture the correct error number and just change it.
  77. If Err = 2501 Then 'The command save record has been cancelled
  78. MsgBox "Save cancelled.", vbInformation, "Info"
  79.  
  80. Else
  81.     MsgBox Err.Description
  82.     Resume Exit_btnsavecorrective_Click
  83. End If
  84. End Sub
  85.  
Aug 13 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

21
by: Stefan Richter | last post by:
Hi, after coding for days on stupid form validations - Like: strings (min / max length), numbers(min / max value), money(min / max value), postcodes(min / max value), telefon numbers, email...
6
by: Darren | last post by:
I have a form that has 10 fields on it. I have made all of them "Required". I also am using vb if statements to decide whether or not each field should be on the page. I am using the vb to...
10
by: iam247 | last post by:
Hi In my prototype asp page (with no javascript and no password validation, I have a registration form with the following action: <form name="form" method="post" action="RegDetails.asp"> ...
16
by: Hosh | last post by:
I have a form on a webpage and want to use JavaScript validation for the form fields. I have searched the web for form validation scripts and have come up with scripts that only validate...
9
by: julie.siebel | last post by:
Hello all! As embarrassing as it is to admit this, I've been designing db driven websites using javascript and vbscript for about 6-7 years now, and I am *horrible* at form validation. To be...
27
by: Chris | last post by:
Hi, I have a form for uploading documents and inserting the data into a mysql db. I would like to validate the form. I have tried a couple of Javascript form validation functions, but it...
11
by: Rik | last post by:
Hello guys, now that I'm that I'm working on my first major 'open' forms (with uncontrolled users I mean, not a secure backend-interface), I'd like to add a lot of possibilities to check wether...
5
by: lucyh3h | last post by:
Hi, I am trying to use XMLHttpRequest to do server side validation. I have several fields on a form and a submit button. The submit button has an event assocated with it when clicked. The...
7
ak1dnar
by: ak1dnar | last post by:
Hi, I got this scripts from this URL There is Error when i submit the form. Line: 54 Error: 'document.getElementbyID(....)' is null or not an object What is this error. Complete Files
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.