Forum OpenACS Q&A: validation

Collapse
Posted by Anny Flores on
I need to validate a variable in ad_form, but I'm having troubles with it because the validation must be in an if statement, right now I'm using -extend but it doesn't work.
  I'll apreciate any help
Collapse
2: Re: validation (response to 1)
Posted by Jeff Lu on
Hi Anny
Can you please post a code snippet so we can help?

There is an example of validation on the api documentation of ad_form by the way.

Collapse
3: Re: validation (response to 1)
Posted by Anny Flores on
The code goes like this:

if { *condition* } {
ad_form -extend -name form_name -validate {
  {var_name
  { *condition* }
    "Message"
  }
}

the problem is that even when the condition of the if statement is true, the validation doesnt work.

Thanks for your help.

Collapse
4: Re: validation (response to 1)
Posted by Jeff Lu on
Here are some notes:
You must always have at least one action block, even if it's just -on_submit { }.
You cannot extend the form after you've supplied any action block.

Sample validation block:
-validate {
        {value
        {[string length $value] >= 3}
        "\"value\" must be a string containing three or more characters"
        }
}

*this means that if the string length is NOT >= 3 it will return the error message "\"value\" must be a string containing three or more characters".

Collapse
5: Re: validation (response to 4)
Posted by Randy O'Meara on
Here's a method I use that utilizes a procedure to validate:

In your form processing page code:

} -validate {
    {value {[valid_value err $value]} $err }
}
"err" is a var parameter that is set by procedure validate_value. On error you set it with the appropriate error message.

And the procedure looks something like:

ad_proc -public valid_value {
    err
    value
} {
    Validates value.
    @return 1 if valid, $err == "".  0 if invalid, $err == descriptive string.
    @param err name of var parameter, in caller's scope, that receives error description.
    @param value the value to be validated.
} {
    upvar 1 $err lerr
    if {[string length $value] < 3} {
	set lerr "\"value\" must be a string containing three or more characters"
	return 0
    }
    set lerr ""
    return 1
}
This might seem like overkill for this simple example, but more complex checks and/or recovery can be performed in a more complex situation.

/R