在表单中显示密码不匹配或其强度的错误消息


Displaying error messages in the form for a password mismatch or its strength

我有以下代码:

<fieldset>
<p>                    
    <label>Password*</label>
    <input type="password" placeholder="Password" name="pswd" id="psd"/>
    <label>Confirm Password*</label>
    <input type="password" name="cpswd" placeholder=" retype Password" id="cpsd" />
    <label class="obinfo">* obligatory fields</label>
</p>
</fieldset>
<?php
    $pwd = $_POST['pswd'];
    if (preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $pwd))
    {
        echo "Your password is good.";
    } 
    else 
    {
        echo "Your password is bad.";
    }
?>

目前代码只是检查密码是否良好(强)。它给出错误 未定义的索引 pswd。我是这方面的新手。我对javascript或jQuery了解不多。有没有办法检查密码强度并查看它们是否使用 php 匹配?也请让我知道如何在表单本身中打印所有消息。提前谢谢。

使用:

<?php
if(isset($_POST['pswd'])){//You need to check if $_POST['pswd'] is set or not as when user visits the page $_POST['pswd'] is not set.
$pwd = $_POST['pswd'];
if (preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $pwd))
    echo "Your password is good.";
 else
    echo "Your password is bad.";
}
?>

首先,确保<form>操作是""或自己的页面名称,因为它看起来就是您想要的。

然后,你应该做

if (isset($_POST['pswd']))
{
    $pwd = $_POST['pswd'];
    if (preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $pwd)){
        echo "Your password is good.";
    } else {
        echo "Your password is bad.";
    }
}

对于使用 jquery 的客户端验证,有很多可用的 jquery 插件给出了一些链接,您可以查看演示,

http://jqueryvalidation.org/http://www.tutorialspoint.com/javascript/javascript_form_validations.htm

http://rickharrison.github.io/validate.js/我个人的建议是使用验证JS。ALOS 也实现了服务器端验证,因为可以在浏览器中禁用 JavaScript。

有关使用 PHP 的服务器端验证,请参阅此链接

http://phpformvalidation.monjur-ul-hasan.info/

希望对您有所帮助。

说真的,你可以使用某种这样的东西:http://jsfiddle.net/3QhBu/,但有一个更好的方法 - 自己做。

$(function(){
    var $spanMsg = $('<span/>', {class: 'span-msg'});
    $('input#psd').on('keyup.checkPswd', function(){
        var $that = $(this);
        var $thisSpanMsg = $that.siblings('span.span-msg').length ? $that.siblings('span.span-msg') : $spanMsg.clone().insertAfter($that);
        if (!/.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$/.test($that.val())) {
            $thisSpanMsg.removeClass('span-msg-green').addClass('span-msg-red').text('Wrong password!');    
        } else {
            $thisSpanMsg.removeClass('span-msg-red').addClass('span-msg-green').text('Password is correct!');
        }
    });
    $('input#cpsd').on('keyup.checkPswdMatch', function(){
        var $that = $(this);
        var $thisSpanMsg = $that.siblings('span.span-msg').length ? $that.siblings('span.span-msg') : $spanMsg.clone().insertAfter($that);
        if ($that.val() != $('input#psd').val()) {
            $thisSpanMsg.removeClass('span-msg-green').addClass('span-msg-red').text('Passwords don''t match!');    
        } else {
            $thisSpanMsg.removeClass('span-msg-red').addClass('span-msg-green').text('Confirm password is correct!');
        }
    });
});