Jump to content

Small form test


NickG21

Recommended Posts

hey everyone, below i have a basic form with a tiny bit of validation code.  the code seems to be processing correctly but initially when i access the site, it displays the text boxes and submit button with the text below "Invalid number scheme" which is my error for the number validation.  could someone tell me the reason this comes through like that?
thank you
[code]<html>
<head>
</head>
<body>
<form action="testing1.php" method="post">
<input type="text" name="text1" value="Your Name"><br/>
<input type="text" name="text2" value="Number"><br/>
<input type="test" name="email"><br/>
<input type="submit" name="submit" value="submit"><br/>
</form>
<?php
$email = $HTTP_POST_VARS['email'];
$name = $HTTP_POST_VARS['text1'];
$number = $HTTP_POST_VARS['text2'];

// check e-mail address
// display success or failure message
if (!preg_match("/^([0-9])+/",$_POST['text2']))
{
die("Invalid Number Scheme");
}
elseif (!preg_match("/^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/",

$_POST['email']))
{
die("Invalid e-mail address");
}
echo "Valid e-mail address, processing...";
?>
</body>
</html>[/code]

Link to comment
https://forums.phpfreaks.com/topic/31422-small-form-test/
Share on other sites

When your script runs, it will both display your form and also run the if else statement. Since $_POST['text2'] will not be set (since you haven't submitted your form yet), the first preg_match will always be false and die with the error "Invalid number scheme"

What you need is another if..else to run your validation/ processing when there is posted data or otherwise print the form.

Also, use $_POST instead of $HTTP_POST_VARS.

[code]
<?php

if($_POST){
$email = $_POST['email'];
$name = $_POST['text1'];
$number = $_POST['text2'];

// check e-mail address
// display success or failure message
if (!preg_match("/^([0-9])+/",$_POST['text2']))
{
die("Invalid Number Scheme");
}
elseif (!preg_match("/^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/", $_POST['email']))
{
die("Invalid e-mail address");
}
echo "Valid e-mail address, processing...";
} else {
?>
<html>
<head>
</head>
<body>
<form action="test3.php" method="post">
<input type="text" name="text1" value="Your Name"><br/>
<input type="text" name="text2" value="Number"><br/>
<input type="text" name="email"><br/>
<input type="submit" name="submit" value="submit"><br/>
</form>
</body>
</html>
<?php } ?>[/code]
Link to comment
https://forums.phpfreaks.com/topic/31422-small-form-test/#findComment-145480
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.