Sunday, April 8, 2012

A very basic AJAX form validation in Oracle APEX

AJAX can be used efficiently with Oracle APEX to create dynamic form validation on the fly. Here is a simple and clumsy example of how it might be of use.


1. Create your Region and form items. For every form item, we would create a corresponding Display Only item as well to hold validation messages.


2. The Javascript/AJAX code to go in Edit Page >> HTML Header and Body Attributes








Here is the full code that is supposed to go above:


<script language="JavaScript" type="text/javascript">


 function chck()
 { 


var txtItem = $v('P1_NUMBER');

if (txtItem != null && !isNaN(txtItem))
{
var get = new htmldb_Get(null,null,'APPLICATION_PROCESS=VALIDATE',0);
get.add('MSG',txtItem);
gReturn = get.get();

if(gReturn)
{
$x('P1_MSG').innerHTML= gReturn;
}
else
{
$x('P1_MSG').innerHTML='nothing to show';
}
get = null;



else if (isNaN(txtItem))
{
$x('P1_MSG').innerHTML='You must enter a number in text box';
}
else
{
$x('P1_MSG').innerHTML='';
}
}

</script>



3. The code makes a call to an Application Process called VALIDATE which I have created (below) in shared Components. It extracts value from the page item with $v( ) and passes it to the application Item MSG.




4. We now create the application process VALIDATE. This will simply run a query to check if the number entered exists in database and output (via htp.p) the appropriate message.






5.  As you can see above, the process makes use of an item called MSG. This is an application Item we create from Shared Components of the application.


6. Lastly we go to the form Item (P1_NUMBER) which will trigger the process with onBlur event. 





You can test it out here: http://apex.oracle.com/pls/apex/f?p=56259:1

Valid Entries: 0123456789