如何使用jQuery使用图标作为通过/失败指示器进行表单验证?

如何使用jQuery使用图标作为通过/失败指示器进行表单验证?,jquery,ajax,validation,Jquery,Ajax,Validation,如何使用jQuery进行表单验证,以便在字段通过正则表达式时允许绿色复选标记,如果失败则允许红色x 有谁能给我举一个jQuery的例子,如果某个字段验证,它会立即显示一个图标,如果它失败,它会显示另一个图标?有多种方法可以实现这一点。这里有一个 相关的HTML如下所示: <div><input type="text" id="myInput" /></div> // probably within your jQuery(document).ready(..

如何使用jQuery进行表单验证,以便在字段通过正则表达式时允许绿色复选标记,如果失败则允许红色x


有谁能给我举一个jQuery的例子,如果某个字段验证,它会立即显示一个图标,如果它失败,它会显示另一个图标?

有多种方法可以实现这一点。这里有一个

相关的HTML如下所示:

<div><input type="text" id="myInput" /></div>
// probably within your jQuery(document).ready(...) function:
// bind a change event handler to your input
jQuery("#myInput").bind("change", function(e) {

    var $this = jQuery(this);
    var re = /[a-z]/; // here's your regex
    var imgSrc = "blank.gif";

    if (re.test(jQuery(this).val())){
        // this is a successful match - green
        imgSrc = "green.gif";         
    } else {
       // this is not a match - red
       imgSrc = "red.gif";
    }

    // make sure we have an image before our input:
    if(!$this.prev().is("img")) { $this.before("img"); }

    // set the image to green
    $this.prev().attr("src", imgSrc);
});
编辑:bug fix+注释

有一种方法支持这类事情。看看“记住牛奶”演示表;它有即时反馈。您可以在validate()方法中设置“success”选项,这样做不仅仅是提供负面反馈;
$(document).ready(AddValidation);

function AddValidation()
{
    $("#frmadminlogin").validate({
        'rules':{
            'txtadminemail':{'required':true, 'email':true},
            'txtadminpass':{'required':true}
        },
        'messages': {
            'txtadminemail':{'required':'<img title="Please enter login email." src="../images/error.gif" />', 'email':'<img title="Please enter valid email." src="../images/error.gif" />'},
            'txtadminpass':{'required':'<img title="Please enter login password." src="../images/error.gif" />'}
        }
    });
}
函数AddValidation() { $(“#frmadminlogin”).validate({ “规则”:{ 'txtadminemail':{'required':true,'email':true}, 'txtadminpass':{'required':true} }, “消息”:{ 'txtadminemail':{'required':'','email':'''}, 'txtadminpass':{'required':'''} } }); }
@Jeff Yang,这很好。你能想出一种方法让我们把大部分内容提取到一个方法中,这样每个字段就不会有那么多重复的代码了吗?