Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Form Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

How to trigger a php function for custom server side form validation?

Go to End

2 Posts   2149 Views


Community Member, 138 Posts

20 September 2010 at 1:57pm


I've been searching around the forums and documentation for a while but am still a bit lost about this. I've got a form which I want to validate server-side by using my own php function.

There's the "php" method in the RequiredFields class: - but I can't find any example of how this would work in the wild.

On the most basic level I'm looking for an example of how to get something like the code to work. This is where a value from a TextField is sent to a function which then returns a message and either does or doesn't validate the field.

$fields = new FieldSet(
    new TextField('Number', 'Enter a Number', '' )

function ValidateNumber($Number){
    if($Number == 10){
        $Message = "You have entered the right number";
        $Validate = true;
    } else {
        $Message = "You have entered the wrong number, try again";
        $Validate = false;

Can someone please show me an example of how this would work inside the sapphire framework?



Forum Moderator, 1899 Posts

1 October 2010 at 2:20am

Edited: 01/10/2010 2:20am

Does this help? (from one of my forms with validation)...

class MyFormPage_Controller extends Page_Controller

	function MyForm()
		$fields= new FieldSet(
			new TextField('MyTextField')

		$actions = new FieldSet(
			new FormAction('ProcessFrom', 'Join')

		$validator = new RequiredFields(

		$form = new Form($this, 'MyForm', $fields, $actions, $validator);
			$previous_value = Session::get("MyFormData");

		return $form;

	function ProcessFrom($data,$form)
		$bValid = true;
		Session::set("MyFormData", $data);

		if($data['MyTextField'] != 'somevalue')
			$form->addErrorMessage('MyTextField','MyTextField is not "somevalue"','required');
			$bValid = false;


		if (!$bValid)
			//failed validation
			return Director::redirectBack();

		//passed validation
		//do stuff with form data
		return Director::redirect(Director::baseURL(). $this->URLSegment.'?posted=1');