我有这个简单的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>
但它不起作用。有人可以帮忙吗?
答案 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个字符
演示: -
<!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;