我们如何在密码框中显示表单验证消息?

时间:2013-08-08 08:55:46

标签: jquery html css validation

有没有办法在密码框中显示表单验证消息?因为当我提交表单时,我没有收到框内的错误消息..我知道它不是文本框,但仍然有可能这样做吗?这是我正在使用的脚本..

<form action="mail.php" id="theform" name="theform" method="post">

 <p><label for="name">Name</label><br />
        <input id="name" type="text" value="" name="name" />
 </p>

 <p><label for="email">E-mail</label><br />
        <input id="email" type="text" value="" name="email" />
 </p>

<p><label for="message">Password</label><br />
        <input id="password" type="password" rows="7" cols="30" name="password"></input>
</p>

<p><input class="submit" type="submit" name="submit" value="Submit Form" />
</p>

 <p id="error">There were errors on the form, please make sure all fields are fill out correctly.</p>
</form>

Jsfiddle

3 个答案:

答案 0 :(得分:1)

我认为您可以将占位符设置为您无效的错误消息,然后重置字段..

就像这里的那个:

http://jsfiddle.net/dUNQn/1

$(document).ready(function(){
// Place ID's of all required fields here.
required = ["name", "email", "message", "password"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
passwerror = "Please enter a valid password";

$("#theform").submit(function(){    
    //Validate required fields
    for (i=0;i<required.length;i++) {
        var input = $('#'+required[i]);
        if ((input.val() == "") || (input.val() == emptyerror)) {
            input.addClass("needsfilled");
            input.val("");
            input.attr("placeholder", emptyerror);
            if( input.attr("type") == "password" ) {
                input.attr("placeholder", passwerror );    
            }
            errornotice.fadeIn(750);
        } else {
            input.removeClass("needsfilled");
        }
    }
    // Validate the e-mail.
    if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
        email.addClass("needsfilled");
        email.val("");
        email.attr("placeholder", emailerror);
    }

    //if any inputs on the page have the class 'needsfilled' the form will not submit
    if ($(":input").hasClass("needsfilled")) {
        return false;
    } else {
        errornotice.hide();
        return true;
    }
});

});

答案 1 :(得分:0)

您需要更改输入的类型,并且不需要jquery:

只是做:

function check() {
    if (document.getElementById("password").value == "") {
        $('#password').get(0).type = 'text';
    } else {
        $('#password')[0].type = 'password';
    }
}

http://jsfiddle.net/6Ce7H/

答案 2 :(得分:0)

if($("#password").val.length==0){
$('#password').attr('type', 'text');
}
else{
$('#password').attr('type', 'password');
}
  1. 在提交时将上述条件添加到您的代码中。
相关问题