Forums

Server Side Validation - Required field

sayf00 28 Jul, 2009
Hi,

This is probably a very simple question, but for the life of me I can't get it working. I'm trying just validate that the first text field (Enter Name) has been filled in and is not empty. I've used the following in the SSV box. If I submit the form with the field empty, I get the "Please enter your name". However if I fill it in and submit I still get the message. What am I doing wrong? Thanks

<?php
if(empty($formVars["text_1"]))

return 'Please enter your name.';
?>
nml375 28 Jul, 2009
Hi,
Your approach is correct, but your variable name is not. All POST-style form field data exist in the superglobal array $_POST[], having each form field name as key, with the corresponding value.

The most trivial way of testing would be something like this:
<?
if (empty($_POST['text_1']))
  return 'Please enter your name.';
?>


/Fredrik
sayf00 30 Jul, 2009
Thanks, that seem to have done the trick.

I hate to be a pain, but the other field I need validated is an "enter email". I just need to make sure it's the corect syntax. The field is "text_7" once again any help is greatly appreciated either the code or a point in the right direction.
nml375 30 Jul, 2009
Hi,
For this, I would recommend some kind of pattern match. The below should do the trick.
<?
if (empty($_POST['text_7']))
{
  return 'Please enter your email address.';
}
elseif (preg_match('/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i', $_POST['text_7']) == 0)
{
  return 'Invalid email address provided: ' . $_POST['text_7'];
}
?>


/Fredrik
sayf00 30 Jul, 2009
Thanks Fredrik, you're a star.
sayf00 30 Jul, 2009
Thanks to Fredrik,

I've now figured out that the following code only allows numbers.
<?php


if (empty($_POST['text_3']))
{
  return 'Please enter your contact number.';
}
elseif (preg_match('/^[0-9]{1,}$/',$_POST['text_3']) ==0)
{
  return 'Invalid contact Number: ' . $_POST['text_3'];
}
?>


My next question is how do I get more than one validation message to appear when the form is submitted? Currently only one is being displayed.
nml375 30 Jul, 2009
I'd suggest you do something like this:

<?
$validationErrors = '';

if (test1)
{
  $validationErrors .= "Test1 failed, please bla bla bla.\n";
}

if (test2)
{
  $validationErrors .= "Test2 failed, please bla bla bla.\n";
}

...

if (!empty($validationErrors))
{
  return $validationErrors;
}
?>


/Fredrik
This topic is locked and no more replies can be posted.