#!shebang path to /cgi-bin/rebol -cs
REBOL [
       Title: "CGI with FORM with refilled data"
        Date: 2-aug-2012
        File: %cgi-form-val-example.r
      Author: "Arnold van Hofwegen"
     Version: 0.0.1     
     Purpose: {
         Example of how a webform could be processed by a REBOL script,
         refilling previously filled fields when errors in input are detected.
         For performance it is always better to have some validation (using 
         e.g. Javascript) on the client side first, but for safety the check
         also needs to be (re)done at the server side.
     }
        library: [
            level: 'intermediate
            platform: 'all
            type: [cgi demo]
            domain: [cgi]
            tested-under: [Core 2.7.8 *nix]
            support: "AltMe"
            license: none
            see-also: none
        ]

]

;-------------------------------------------------------------------
; This script uses the safe-cgi-data-read.r script
; At this moment I do not recommend using this script in a place for 
; public use, i.e. to provide webcomments and other services.
; I use an extended version of this script to put articles on my
; website from a protected directory.
; Improvements and suggestions are more than welcome.
;-------------------------------------------------------------------

do %path to your/cgi-bin/safe-cgi-data-read.r
cgi-block: safe-cgi-data-read

print "Content-Type: text/html^/"  ;-- Required Page Header

; Declaration and emit function from the cookbook:
; http://www.rebol.net/cookbook/recipes/0006.html
html: make string! 10000
emit: func [code] [repend html code]

; Start of the webpage holding the form
emit [
    
     "CGI Form processing with validation and field refill" 
    
    
    
    newline
    
    newline
]

error-field-title: error-field-article: copy ""
title-text: article-text: copy ""
number-of-errors: 0

; Check for valid input, this validation should probably be very much more thorough!
if  0 < length? to-string cgi-block [
    emit [
"The form was send with some data. Results are shown."

newline ] either not empty? cgi-block/title_text [ error-field-title: copy "" title-text: cgi-block/title_text ][ number-of-errors: number-of-errors + 1 error-field-title: " The title field must not be empty. " ] either not empty? cgi-block/article_text [ error-field-article: copy "" article-text: cgi-block/article_text ][ number-of-errors: number-of-errors + 1 error-field-article: " The article field must not be empty. " ] either 0 = number-of-errors [ ; Do some processing here, like putting the data into your mysql database. ; Depending on that result show an appropriate message. emit [
"Site updated at " now
] ][ emit [
"Error(s) found: Site not updated!"
] ] ] ; There is some fun putting a Javascript in here. emit [ newline newline newline
"Add a new article:"

error-field-title

error-field-article

] print html