在我的网页上,我有一个表单,用户可以在其中输入文章的信息。现在,我使用jQuery检查输入的值是否不为空,如果输入的值不为空,则显示错误消息。

当前验证

//Story Form
$('.error').hide(); //Hide error message initially

$(".button").click(function() {         //On button click
    $('.error').hide();
    var title = $("input#sc_title").val();
    if (title == "") {                    //if title is empty
        $("label#title_error").show();        //show error
        $("input#sc_title").focus();          //focus on title field
        return false;
    }
});


现在,它仅检查title == ""。我将如何编辑代码以检查是否至少输入了10个字符,例如如果标题为空且输入的字符数少于10个,是否显示错误?

最佳答案

如果用户在这种情况下在标题字段中输入20个空格字符,则title.length返回20并且满足真实条件,因此您也可以使用jquery trim

if ($.trim(title) == "" || $.trim(title).length < 10) {
    $("label#title_error").show();        //show error
    $("input#sc_title").focus();          //focus on title field
    return false;
}

关于javascript - jQuery验证表单(检查至少10个字符和特定值),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8397908/

10-09 07:07
查看更多