简体   繁体   中英

Form validation error messages php

I've got the following form:

 <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" id="submit-form">
      <label for='fname'>Name</label>
      <input type='text' name="customer" value="" id="customer" maxlength='50'/>
      <?php echo "<h1>$errName</h1>" ?>
      <label for='fname'>Company Name</label>
      <input type='text' name="company" value="" id="company" maxlength='50' />
      <label for='email'>Email Address</label>
      <input type='text' name='email' value="" id='email' maxlength='50'/>
      <label for='number'>Telephone Number</label>
      <input type='text' name="phone" value="" id="phone" maxlength='20'/>
      <input type="hidden" name="campaign" id="campaign" value="Getting Started" maxlength='300'>
      <input type='submit' name="submit-btn" id="submit-btn" value='Send Request'/>
    </form>

When I submit it I run the following PHP :

function validate_input($data, $type) {

        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);

        switch ($type) {
            case "name": //letters 
                if (!preg_match('/^[a-zA-Z ]{2,80}+$/', $data)) {
                    $errName = "Name can only contain letters";
                    $errors = true;
                }
                break;
            case "email":
                if (!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $data)) {
                    $errEmail = "Email must be valid format";
                    $errors = true;
                }
                break;
            case "company": //letters and numbers
                if (!preg_match('/^[a-zA-Z0-9 ]{2,80}+$/', $data)) {
                    $errCompany = "Company can only contain letters or numbers";
                    $errors = true;
                }
                break;
            case "number": //digits, spaces and hypens
                if (!preg_match('/^[\d -.]*\d$/', $data)) {
                    $errNumber = "Phone must be valid format";
                    $errors = true;
                }
                break;
            case "campaign":
                if (!preg_match('/^[a-zA-Z0-9 ]{2,80}+$/', $data)) {
                    $errCampaign = "Campaign must be valid format";
                    $errors = true;
                }
                break;
        }
        return $data;
    }

    //Check form was submitted
    if (isset($_POST['submit-btn'])) {
        $errors = false;
        $errName = $errEmail = $errCompany = $errPhone = $errCampaign = "";
        $name = $email = $company = $phone = $campaign = "";
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $name = validate_input($_POST['customer'], "name");
            $email = validate_input($_POST['email'], "email");
            $company = validate_input($_POST['company'], "company");
            $phone = validate_input($_POST['phone'], "number");
            $campaign = validate_input($_POST['campaign'], "campaign");
        }

        if ($errors == false) {
            //Send email to sales team
            $to = "test@gmail.com";
            $from = $email;
            $subject = "Test Email";
            $message = "Customer Name: " . $name
                    . "\r\nEmail Address: " . $email
                    . "\r\nCompany: " . $company
                    . "\r\nPhone Number: " . $phone
                    . "\r\nCampaign Type: " . $campaign;
            $headers = "From: " . $from;
            mail($to, $subject, $message, $headers);

            //Send email to customer
            $to = $email;
            $from = "test@gmail";
            $subject = "Thank you for your Enquiry:";
            $message = "Dear " . $name . ",\r\nThank you for getting in contact. One of our team will be in touch with you shortly.";
            $headers = "From: " . $from;
            mail($to, $subject, $message, $headers);
        }
    }

I'm having trouble showing an error message for the name field. The regular expression only permits Letters and spaces. If someone puts in input like 12348jack then the $error variable should be set to true and the email should not be sent.

However each time I do this the email is sent and no error message is shown on my form.

Could anyone point me in the right direction as to where I am going wrong?

Many thanks

I think this is a scope issue.

You are basing the creation of the email of this test

 if ($errors == false) {

     ....

But you are never actually setting the $errors in the validate_input because it is out of scope.

I suggest that you change the function to pass the $errors variable like so. Note the use of &$

function validate_input($data, $type, &$errors) {

Then your function will have access to it.

So your validation calls will be

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = validate_input($_POST['customer'], "name", $errors);
    $email = validate_input($_POST['email'], "email", $errors);
    $company = validate_input($_POST['company'], "company", $errors);
    $phone = validate_input($_POST['phone'], "number", $errors);
    $campaign = validate_input($_POST['campaign'], "campaign", $errors);
}

this is a scope issue

you can use global keyword in your validate function

function validate_input($data, $type) {
global $errors;
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
....

and I recommend @RiggsFolly solution too

Why don't create a variable which contains all the HTML code, then output to video by echo, so if you want to create a validation and manage HTML code.

$fields = array ('name'=> '<input type='text' name="customer" value="" id="customer" maxlength='50'/>'...[all your form components]...);

if(!empty($_POST)){
    $validate_input($postedData,$postedType);
}

In the validate_input function create the array of errors

$this->errors['name'] = "Name can only contain letters" ;

And then where you want to render

 $buffer = <form method="post" action=" htmlspecialchars($_SERVER['PHP_SELF']) " id="submit-form">
    foreach (fields as $key => $htmlCode){
        $buffer.= "<label>$key</label><".$htmlCode.">;
        if(!empty($this->errors[$key])
            $buffer.="<label class='error'>".$this->errors[$key]."</label>";

    }

This portion of code is untested, but I hope I've given you the idea

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM