简体   繁体   中英

Checking if the input name and telephone number valid with php

I have tried this code to add validation when the input is name and number. But, there is something wrong with this code. The validation for nama and telepon are always wrong. I use the form and validation in one page.Can you help me solve this problem

<?php
error_reporting(E_ALL);
class   ValidateInfo
    {
        public  $errors;
        public  $message;
        public  $data;
        public  $wrong;
        public  $wrongmessage;
        public  function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
            {
                $trimmed                =   trim($payload[$type]);

                if(!empty($validate)) {
                        // Strip out all but numbers
                        if(in_array('digits',$validate)) {
                            if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {
                            // not an integer!
                                $this->wrong[$type] = 1;
                                $this->wrongmessage[$type] = 'Telephon number must be in number';
                            } else {
                                $this->wrong[$type] = 0;
                            }
                        }
                        // Strip out letters
                        elseif(in_array('letters',$validate)) {
                            if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === true) {
                            // not an integer!
                                $this->wrong[$type] = 1;
                                $this->wrongmessage[$type] = 'Name must be in alphabet';
                            } else {
                                $this->wrong[$type] = 0;
                            }
                        }
                        // Re-assign data type to consolidate
                        $this->data[$type]          =   (!isset($this->data[$type]))? $trimmed:$this->data[$type];

                        // Check if data is an email
                        if(in_array('email',$validate)) {
                            if(filter_var($this->data[$type], FILTER_VALIDATE_EMAIL) === false){
                                $this->wrong[$type] = 1;
                                $this->wrongmessage[$type] = 'Tulis email seperti: yourname@email.com';
                            } else {
                                $this->wrong[$type] = 0;
                            }
                        }

                        // Strip out html tags
                        if(in_array('strip',$validate)) {
                                $this->data[$type]  =   strip_tags($this->data[$type]);
                            }
                    }

                if(!isset($this->data[$type]))
                    $this->data[$type]  =   $trimmed;

                $this->errors[$type]    =   (empty($this->data[$type]))? 1:0;
                $this->message[$type]   =   $mess;
            }
    }

// Creat instance of info processor
$info   =   new ValidateInfo(); 

// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {

    // Checks empty fields
    $info->Check($_POST,'nama','Write your name',array('letters'));
    $info->Check($_POST,'telepon','Write the phone number',array('digits'));
    $info->Check($_POST,'email','Write the email',array('email'));
    $info->Check($_POST,'judul','Write the title');
    $info->Check($_POST,'konten','Write the content');

    if(array_sum($info->errors) == 0 && array_sum($info->wrong) == 0) {

        // path and name of the file
        $filetxt    =   'dataInJson.json';

        // Assign stored data
        $data       =   $info->data;

        // path and name of the file
        $filetxt    =   'dataInJson.json';

        // to store all form data
        $arr_data   =   array();        

        // gets json-data from file
        $jsondata   =   file_get_contents($filetxt);

        // converts json string into array
        $arr_data   =   json_decode($jsondata, true);

        // appends the array with new form data
        $arr_data[] =   $data;

        // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
        $jsondata   =   json_encode($arr_data, JSON_PRETTY_PRINT);

        // saves the json string in "dataInJson.json"
        // outputs error message if data cannot be saved
        if(file_put_contents('dataInJson.json', $jsondata)) {
            $info->errors['success']    =   true; ?>
                <script type="text/javascript">alert("Data has been submitted");</script>
  <?php }
        else {
            $info->message['general']['put_file']   =   'Tidak dapat menyimpan data di "dataInJson.json"';
        }
    }
}
else 
    $info->message['general']['submit'] =   'Form fields not submited'; ?>

<head>
 <title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet'    type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>

<body>
<div class="center">
<h1>Data Buku</h1>

<?php if(isset($info->errors['success'])) { ?>
    <h2>Thank you!</h2>
<?php } else { ?>
<p><span class="error">* required field.</span></p>
<?php } ?>
<hr>
<form action="" method="post">
    <?php if(isset($info->message['general'])) {
        foreach($info->message['general'] as $_error) { ?>
        <span class="error">* <?php echo $_error; ?></span><br>
        <?php
            }
    } ?>

    <h2>Informasi Pengarang</h2>

    <div class="roadie">
        <label for="nama">Nama:</label>
        <input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value="     <?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
        <?php 
            if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?>
                <span class="error">* <?php echo $info->message['nama']; ?></span><?php 
            } 
            if(isset($info->wrong['nama']) && $info->wrong['nama'] == 1) { ?>
                <span class="error">* <?php echo $info->wrongmessage['nama']; ?></span><br><?php 
            }?>
    </div>

    <div class="roadie">
        <label for="telepon">Nomor Telepon:</label>
        <input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
    <?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?><span    class="error">* <?php echo $info->message['telepon']; ?></span><?php } 
    if(isset($info->wrong['telepon']) && $info->wrong['telepon'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['telepon']; ?></span><br><?php } ?>
    </div>

    <div class="roadie">
        <label for="email">e-Mail:</label>
        <input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
    <?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?><span class="error">* <?php echo $info->message['email']; ?></span><br><?php }
        if(isset($info->wrong['email']) && $info->wrong['email'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['email']; ?></span><br><?php }
        ?>
    </div>

    <div class="roadie">
    <h2>Tulisan</h2>
        <label for="judul">Judul:</label>
        <input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
    <?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?><span class="error">* <?php echo $info->message['judul']; ?></span><?php } ?>
    </div>

    <div class="roadie">
        <label for="konten">Konten:</label>
        <textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) {  echo strip_tags($info->data['konten']); } ?></textarea>
    <?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?><span class="error">* <?php echo $info->message['konten']; ?></span><br><?php } ?>
    </div>

    <input type="submit" id="submit" name = submit value="Create" />
    <input type="reset" id="reset" value="Reset" />
</form>


I debugged your code, and the problem is:

When your program checks your nama field, it has option array('letters') for $validate .

 elseif (in_array('letters', $validate)) {
     if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {

So when you want to check letters, why do you use FILTER_VALIDATE_INT ?

The other problem is here:

if(!isset($this->data[$type])) {
    $this->data[$type]  =   $trimmed;
}
$this->errors[$type]    =   (empty($this->data[$type]))? 1:0;
$this->message[$type]   =   $mess;

This block is at the end of your Check. So, when first run, you try to check an empty thing, and then when method finishes, the nama will be added to the $this->data . This is why your second Check call does not found the telpone. So move this block to the top of your method, and validate, is this exists. Validate formats only after this check.

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