Results 1 to 9 of 9

Thread: pregmatch for name field not working in validation

  1. #1
    Join Date
    Sep 2017
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default pregmatch for name field not working in validation

    Code:
    <?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>
    Last edited by jscheuer1; 09-24-2017 at 10:15 PM. Reason: format code

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,497
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Looks right to me, however, as far as I can see:

    test_input

    is not defined. So try it without that line:

    Code:
         $name = test_input($_POST["name"]);
    Use this line instead:

    Code:
         $name = $_POST["name"];
    or just dispense with the intermediate variable.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Sep 2017
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default

    Hi i tried this code but pregmatch is not working.....

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,497
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    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:

    Code:
    <?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:

    Code:
    $nameError = "Only letters and white space allowed";
    to:

    Code:
    $nameErr = "Only letters and white space allowed";
    because $nameError isn't used anywhere else.
    Last edited by jscheuer1; 09-25-2017 at 07:05 PM. Reason: add info
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. The Following User Says Thank You to jscheuer1 For This Useful Post:

    pkrishna42 (09-28-2017)

  6. #5
    Join Date
    Jan 2015
    Posts
    78
    Thanks
    0
    Thanked 19 Times in 19 Posts

    Default

    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.
    Last edited by DyDr; 09-26-2017 at 01:44 PM. Reason: more info

  7. #6
    Join Date
    Jan 2015
    Posts
    78
    Thanks
    0
    Thanked 19 Times in 19 Posts

    Default

    Here is an example of using the suggestions listed above -
    PHP Code:
    <?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>

  8. The Following User Says Thank You to DyDr For This Useful Post:

    pkrishna42 (09-28-2017)

  9. #7
    Join Date
    Sep 2017
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default

    Hi the above coding is working good but I am not able to echo the variables

  10. #8
    Join Date
    Jan 2015
    Posts
    78
    Thanks
    0
    Thanked 19 Times in 19 Posts

    Default

    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

  11. #9
    Join Date
    Sep 2017
    Posts
    20
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default

    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)
    Last edited by pkrishna42; 10-03-2017 at 07:20 AM.

Similar Threads

  1. Field validation w/js and jquery
    By sme in forum JavaScript
    Replies: 2
    Last Post: 03-12-2012, 05:04 PM
  2. Form field validation
    By Dragonwalker in forum HTML
    Replies: 3
    Last Post: 07-14-2010, 11:15 PM
  3. Field Validation and images
    By n0131378 in forum JavaScript
    Replies: 5
    Last Post: 11-05-2008, 06:02 PM
  4. Need help with Required field(s) validation
    By nmasuda in forum Dynamic Drive scripts help
    Replies: 1
    Last Post: 05-03-2007, 11:21 PM
  5. Required field(s) validation
    By aolson in forum Dynamic Drive scripts help
    Replies: 6
    Last Post: 11-22-2005, 09:28 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •