laurence keith albano laurence keith albano - 3 months ago 18
HTML Question

How to setCustomValidity when username is less than 4 characters?

I have this simple html and Jquery code. I want to set the setCustomValidity to appear when user inputs 4 characters in the textfield. So far I'm not getting such result in my code:

<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>


I tried this:

<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>


But it doesn't work. Can anyone help?

Answer

friend why you are not using html5 pattern like

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

Note : Now user cant able to enter less than 5 character in user text field

Demo:-

<!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>

Comments