Validating Page Objects

When you have a large number of input elements on a form, how do you check that the user has not left any blank?

Traditionally in ASP, you would check each element individually either with client-side or server-side script. However there is a much better technique for doing this. This example is using VBscript but could easily be adapted to Javascript if preferred.

The first step is to have a "key" marker in each of the items to be validated:

<input type="text" id="textfield1_chk" value="">
<input type="text" id="textfield2_chk" value="">
<input type="text" id="cost1_chk" value="">

<input type="text" id="textfield13" value="">

Here the input elements to be checked all have the suffix "_chk" appended to their name, the element called "textfield13" will NOT be validated in this instance.

Next we declare the following client-side script in the <head> of the page. This example assumes all elements are contained in a form object called "form1" and there is a button on the page called "ConfirmBtn":

<script language="vbscript">
function ConfirmBtn_onclick()
ValidationError = False
strErrorList = ""
for each obj in document.form1.elements
  if instr(obj.id, "_chk") > 0 then
    if obj.value = "" then
      obj.backColor = "Red"
      ValidationError = true
    end if
  end if
next

if not(ValidationError) then
  form1.submit()
else
  alert("Please enter information in the fields highlighted in RED")
end if
end function
</script>

Now when the user presses the button to submit the form, they will get a pop-up warning message AND any mandatory fields which have been left blank will be highlighted in RED so they can easily see what is left to fill in - really handy if you have a lot of fields on screen.

Text Field 1:

Text Field 2:

Text Field 3:

Text Field 4:

Text Field 5: