用户名小于4个字符时如何设置自定义值?

时间:2016-08-25 03:03:50

标签: javascript jquery html

我有这个简单的html和Jquery代码。我想将setCustomValidity设置为当用户在文本字段中输入4个字符时出现。到目前为止,我没有在我的代码中得到这样的结果:

<html>
<body>

    <input type="text" placeholder="Username" oninvalid="setCustomValidity('Please enter username')" oninput="setCustomValidity('')" id="username" name="username"" required>

</body>
<script>
    var username = $("#username").val();

    if (username.strlen < 4) {
        username.setCustomValidity('Username must contain at least 5 characters');
    } else {
        username.setCustomValidity('');
    }

    $(document).ready(function() {
        $("#username").keyup(checkUsername);
    });
</script>
</html>

我试过了:

<script>
    var username = $("#username").val();

    if (username.strlen < 4) {
        username.setCustomValidity('Username must contain at least 5 characters');
    } else {
        username.setCustomValidity('');
    }

    $(document).ready(function() {
        $("#username").keyup(checkUsername);
    });
</script>

但它不起作用。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

字符串中没有strlen方法。您可能想要使用length

所以它应该是......

if (username.length <= 4)

我不确定您的邮件的<==是否与您的标题相矛盾。我是说这个。 Username must contain at least 5 characters但标题为username is less than 4 characters

答案 1 :(得分:1)

朋友你为什么不使用html5模式

    <input type="text" placeholder="Username"  pattern=".{5,}" title="Username must contain at least 5 characters" required id="username" name="username">

注意:现在用户无法在用户文本字段中输入少于5个字符

演示: -

&#13;
&#13;
<!DOCTYPE html>
<html>
<body>
<form action="youractionpage.php">
  <input type="text" placeholder="Username"  pattern=".{5,}" title="Username must contain at least 5 characters" required id="username" name="username">
<input type="submit" value="ok">
</form>
</body>

</html>
&#13;
&#13;
&#13;