如何使用php验证输入字段

时间:2016-07-13 14:44:44

标签: php jquery html forms

如何验证用户在联系表单中输入的联系号码实际上是否为号码且至少为10个号码?意思是我希望输入字段只接受10个或更多的数字,并且还接受加号(+)。目前,php会验证所有字段是否已完成且电子邮件是否正确。

这是html代码:

            <div class="contact-form">
                <form id="contact-form" action="sendmail.php" method="post" title="Contact Form" role="form">
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label for="contact-name">Full name</label>
                            <input type="text" name="name" placeholder="Enter your full name..." class="contact-name" id="contact-name">
                        </div>
                        <div class="form-group">
                            <label for="contact-email">Email</label>
                            <input type="text" name="email" placeholder="Enter your email..." class="contact-email" id="contact-email">
                        </div>
                        <div class="form-group">
                            <label for="contact-number">Contact number</label>
                            <input type="text" name="number" class="active" id="contact-number" placeholder="Your contact number...">
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label for="contact-message">Message</label>
                            <textarea name="message" placeholder="Your message..." class="contact-message" id="contact-message"></textarea>
                        </div>
                    </div>
                    <div class="col-sm-12 text-center">
                        <button type="submit" class="btn btn-default sketchFlowPrint" id="submit">Send</button>
                    </div>
                </form>
          </div>

这是php代码:

<?php

// Email address verification
function isEmail($email) {
    return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};

if($_POST) {

    // Enter the email where you want to receive the message
    $emailTo = 'example@gmail.com';

    $clientName = addslashes(trim($_POST['name']));
    $clientEmail = addslashes(trim($_POST['email']));
    $number = addslashes(trim($_POST['number']));
    $message = addslashes(trim($_POST['message']));

    $subject = 'Query from My Domain';

    $sendMessage = 'Hi' . "\n\n";
    $sendMessage .= $message . "\n\n";
    $sendMessage .= 'From: ' . $clientName . "\n";
    $sendMessage .= 'Email: ' . $clientEmail . "\n";
    $sendMessage .= 'Contact number: ' . $number . "\n";

    $array = array();
    $array['nameMessage'] = '';
    $array['emailMessage'] = '';
    $array['numberMessage'] = '';
    $array['messageMessage'] = '';

    if($clientName == '') {
        $array['nameMessage'] = 'Please enter your full name.';
    }
    if(!isEmail($clientEmail)) {
        $array['emailMessage'] = 'Please insert a valid email address.';
    }
    if($number == '') {
        $array['numberMessage'] = 'Please enter a valid contact number.';
    }
    if($message == '') {
        $array['messageMessage'] = 'Please enter your message.';
    }
    if($clientName != '' && isEmail($clientEmail) && $message != '') {
    // Send email
    $headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
    $headers .= PHP_EOL;
    $headers .= "MIME-Version: 1.0".PHP_EOL;
    $headers .= "Content-Type: multipart/mixed;".PHP_EOL;
    $headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
    mail($emailTo, $subject, $sendMessage, $headers);
    }

    echo json_encode($array);

}   else {
        header ('location: index.html#contact');
}

?>

这是jQuery:

// Contact form 
$('.contact-form form').submit(function(e) {
    e.preventDefault();

    var form = $(this);
    var nameLabel = form.find('label[for="contact-name"]');
    var emailLabel = form.find('label[for="contact-email"]');
    var numberLabel = form.find('label[for="contact-number"]');
    var messageLabel = form.find('label[for="contact-message"]');

    nameLabel.html('Full name');
    emailLabel.html('Email');
    numberLabel.html('Contact number');
    messageLabel.html('Message');

    var postdata = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'sendmail.php',
        data: postdata,
        dataType: 'json',
        success: function(json) {
            if(json.nameMessage !== '') {
                nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
            }
            if(json.emailMessage !== '') {
                emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
            }
            if(json.numberMessage !== '') {
                numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
            }
            if(json.messageMessage !== '') {
                messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
            }
            if(json.nameMessage === '' && json.emailMessage === '' && json.numberMessage === '' && json.messageMessage === '') {
                form.fadeOut('fast', function() {
                    form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
                });
            } 
        }
    });
});

2 个答案:

答案 0 :(得分:2)

我猜测+需要成为第一个角色(国际电话号码)?

然后这应该这样做:

if (!preg_match('/^(\+?)+([0-9]{10,})$/', $number)) {
    $array['numberMessage'] = 'Please enter a valid contact number.'
}

加号是可选的。如果需要,只需删除表达式中加号后的?

答案 1 :(得分:0)

检查长度是否小于10或查看输入是否与过滤输入不同(+和数字已删除)。

<?php
function valid_tel($in) {
    $valid = true;
    if(strlen($in) < 10 || $in !== preg_replace('@[^0-9+]@','', $in)) {
        $valid = false;
    }

    return $valid;
}
var_dump(valid_tel(''));
var_dump(valid_tel('01234'));
var_dump(valid_tel('01234567890')); // 11 long
var_dump(valid_tel('+012345678')); // 10 inc +
var_dump(valid_tel('+0123456'));
var_dump(valid_tel('0123456xyz7890'));

输出:

boolean false
boolean false
boolean true
boolean true
boolean false
boolean false