View Full Version : pregmatch for name field not working in validation
pkrishna42
09-24-2017, 07:18 PM
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" and !empty($_POST["name"]) and isset($_POST['state']) and ($_POST['state'] !== 'NULL') and isset($_POST['city']) and $_POST['city'] !== 'NULL'){
header('location:sucess.php');
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
if(isset($_POST['state'])) {
if($_POST['state'] == 'NULL') {
echo '<p>Please select state.</p>';
} }
if(isset($_POST['city'])) {
if($_POST['city'] == 'NULL') {
echo '<p>Please select city.</p>';
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Please select a state</legend>
<select name="state">
<option value="NULL">-- Please select a state --</option>
<option value="Member" <?php if(isset($_POST['state']) && $_POST['state']=="Member") { ?>selected<?php } ?>>Member</option>
<option value="New" <?php if(isset($_POST['state']) && $_POST['state']=="New") { ?>selected<?php } ?>>New</option>
<option value="one" <?php if(isset($_POST['state']) && $_POST['state']=="one") { ?>selected<?php } ?>>one</option>
</select>
<select name="city">
<option value="NULL">-- Please select a state --</option>
<option value="Member" <?php if(isset($_POST['city']) && $_POST['city']=="Member") { ?>selected<?php } ?>>Member</option>
<option value="New" <?php if(isset($_POST['city']) && $_POST['city']=="New") { ?>selected<?php } ?>>New</option>
<option value="one" <?php if(isset($_POST['city']) && $_POST['city']=="one") { ?>selected<?php } ?>>one</option>
</select>
<input type="text" name="phone">
<input type="tel" name="name" id="name" value="<?php echo isset($_POST["name"]) ? $_POST["name"] : ''; ?>"> <?php echo $nameErr;?>
<input type="submit" name="submit" value="submit">
</fieldset>
</form>
</body>
</html>
jscheuer1
09-25-2017, 04:44 PM
Looks right to me, however, as far as I can see:
test_input
is not defined. So try it without that line:
$name = test_input($_POST["name"]);
Use this line instead:
$name = $_POST["name"];
or just dispense with the intermediate variable.
pkrishna42
09-25-2017, 06:06 PM
Hi i tried this code but pregmatch is not working.....
jscheuer1
09-25-2017, 06:30 PM
Oh, it's probably working, the problem I see now, is that if name and all the other things are set, it never gets that far. Try also adding it at the top:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" and !empty($_POST["name"]) and preg_match("/^[a-zA-Z ]*$/",$_POST["name"]) and isset($_POST['state']) and ($_POST['state'] !== 'NULL') and isset($_POST['city']) and $_POST['city'] !== 'NULL'){
header('location:sucess.php');
}
?>
Oh, and you should change:
$nameError = "Only letters and white space allowed";
to:
$nameErr = "Only letters and white space allowed";
because $nameError isn't used anywhere else.
This code is repetitive, making it hard to write, test, and maintain. Also, the end result of processing the form data should be to do something with the submitted data. The code currently isn't doing anything and redirecting to a success page won't carry the submitted form data with it.
If you organize the code as follows, you can more easily get it to do what you want -
1) Put ALL the form processing code near the top of the file, before the start of the html document.
2) Use an array to hold the ALL the validation error messages. You currently have a mix of storing error messages in discrete variables and echoing them directly. The array holding the error messages is also an error 'flag' that you can test to determine if there are any errors or not. If the array is empty, there are no errors. If the array is not empty, there are errors. This will eliminate the need for discrete error variable(s) that are just cluttering up your code. If you use the form field name as the array index, you can reference individual errors if you want to output them next to the form fields they correspond to, which again, you are not constantly doing in your code. Some of your error messages are being output above the form, the other, for the name field is being output next to the field it corresponds to.
3) After validating all the inputs, if there are no errors, use the submitted form data. It's not clear yet if this is some sort of registration process or a search form. If this a search form, you need to use method='get' for the form.
4) Only after successfully validating and using the submitted form data (there can be additional errors as part of using the submitted form data) should you redirect to a success page.
Next, forget about the test_input() function. It's something copied from w3schools and isn't properly coded. You should only trim the submitted form data, before doing any validation on it so that you can detect if all white-space characters where submitted. The logic copied from w3schools is backwards and is testing for empty() data first, then applying test_input(), which is trimming data, so it will allow all white-space data to result in an empty value when you finally use the data.
You should not use the string NULL for the default select/option values. The NULL keyword has meaning in programming languages and using a string value that's the same as a language keyword is only going to cause confusion. Just use an empty string for the default select/option value.
Don't use isset() on values that WILL be set. This is just adding unnecessary logic that you must maintain and will hide typo errors in your form field/php code names. After you have detected that a post method form has been submitted, except for unchecked checkbox/radio-buttons, all form fields will be set. There's no good reason to use isset() on them.
Don't echo the raw $_SERVER['PHP_SELF'] value. It allows cross-site-scripting. For html5 (the doctype you are using), you can just leave the action='...' attribute out of the form tag.
You should produce the select/option choices dynamically, by using an array to define the choices and looping over the array to produce the output. This will eliminate the need to repeat all that code and markup for each choice and will allow you to change the list of options simply by changing the list defined in the array.
It's not clear if you are trying to input a phone number or a name, but the type='tel' form field isn't supported in all browsers and you should not use it. In any case, the form field names should match the meaning of the data.
When you output data to the browser, you should apply htmlentities() to the values so that any html entities, such as javascript in the data, won't be rendered by the browser.
Edit: The header() redirect needs an exit;/die; statement after it to stop program execution.
This list of items will actually simplify and clean up the code and make it easier to write, test, or make changes to.
If I get a chance I will post an example showing these items.
Here is an example of using the suggestions listed above -
<?php
// some 'helper' functions -
// apply html htmlentities to a value
function _ent($val)
{
return htmlentities($val);
}
// return an element from an array
function _element($arr,$index)
{
return isset($arr[$index]) ? $arr[$index] : '';
}
$errors = []; // define an array to hold errors
$data = []; // define an array to hold a working copy of the data being operated on (if editing existing data, this is needed. for commonality, use if just submitting new data too.)
// define a list of option choices - both city/state are using the same list. if they were different lists, create two separate defining arrays.
$options = ['Member','New','one'];
// form processing
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$data = array_map('trim',$_POST); // get a trimmed copy of all 1st level (non-array) data
// validate all the inputs here
// state and city - select/option, consisting of Member, New, one.
// name - text field, consisting of letters and spaces only.
// phone - unknown if used, but using this recommend code layout, adding code for a field is straight forward.
if($data['state'] == '')
{
$errors['state'] = "State is required.";
}
else
{
if(!in_array($data['state'],$options))
{
$errors['state'] = "Invalid choice for State."; // if you see this error, either there is a mistake in the coding or someone is submitting their own values.
}
}
if($data['city'] == '')
{
$errors['city'] = "City is required.";
}
else
{
if(!in_array($data['city'],$options))
{
$errors['city'] = "Invalid choice for City."; // if you see this error, either there is a mistake in the coding or someone is submitting their own values.
}
}
if($data['name'] == '')
{
$errors['name'] = "Name is required.";
}
else
{
if (!preg_match("/^[a-zA-Z ]*$/",$data['name']))
{
$errors['name'] = "Only letters and spaces are allowed in Name."; // allowing actual white space, which the original message stated uses a different value in the regex pattern
}
}
// if no errors, use the submitted data
if(empty($errors))
{
// do 'something' with the submitted form data in $data
// generate a fake error message
$errors[] = 'For testing, stay on this page after the form data has been processed';
}
// if no errors at this point, the form data was successfully processed
if(empty($errors))
{
header('location:success.php'); // note: success was misspelled in the original code
die;
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
// if you want to display all the errors at once, before the start of the form, do that here...
if(!empty($errors))
{
echo implode('<br>',$errors); // add any html markup and css to display them the way you want
}
?>
<form method="post">
<fieldset>
<legend>Please select a state</legend>
<select name="state">
<option value="">-- Please select a state --</option>
<?php
foreach($options as $choice)
{
$sel = isset($data['state']) && $data['state'] == $choice ? ' selected' : '';
echo "<option value='$choice'$sel>$choice</option>\n";
}
?>
</select>
<select name="city">
<option value="">-- Please select a city --</option>
<?php
foreach($options as $choice)
{
$sel = isset($data['city']) && $data['city'] == $choice ? ' selected' : '';
echo "<option value='$choice'$sel>$choice</option>\n";
}
?>
</select>
<input type="text" name="name" value="<?= _ent(_element($data,'name')); ?>"> <?= _element($errors,'name'); ?>
<input type="submit" name="submit" value="submit">
</fieldset>
</form>
</body>
</html>
pkrishna42
09-29-2017, 12:19 PM
Hi the above coding is working good but I am not able to echo the variables
You would need to post the code that you need help with. I suspect it is code in // do 'something' with the submitted form data in $data
pkrishna42
10-03-2017, 06:48 AM
I want to validate phone number in this format
1 222 123 1234
1 333 123 1234
1231231234
1-123-123-1234
1123-123-1234
123-123-1234
My code
preg_match("/^([0-9]){3}[0-9]{3}-[0-9]{4}$/", $field)
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.