Reputation: 164
I'm trying to set a Second validation message for my password input, but it doesn't work, can you help me out?
This is my tag:
<input id="password" style="text-align:center;" type="text" name="password"
tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required
oninvalid="this.setCustomValidity('Please enter a password')"
oninput="this.setCustomValidity('')"
onkeyup="deleteBadConfirm(); valid_pass();" />
and this is mu js function for the second validation message:
function valid_pass() {
if(document.getElementById("password").value != "") {
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don't use any symbols');
};
};
function deleteBadConfirm() {
$("#confirmpassword").prop("value", "");
};
EDIT: This is how it's supposed to go down: if the user press submit before entering a password, the message says "please enter a password". Then, if the user enters a password, but it's not valid, this time the message should say"At least, enter 6 ...". Now, it shows the first message, but then, if I enter less than 6 characters, it still brings up the old message, and if I enter 6 invalid characters, it won't show any message!!
Upvotes: 2
Views: 395
Reputation: 395
Clear the oninvalid
event or it will always override your setCustomValidity
. Added the :invalid
CSS pseudo-class to check if value is valid or not.
function valid_pass() {
if (document.getElementById("password").value != "") {
if ($('#password').is(":invalid")) {
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don\'t use any symbols');
};
} else {
document.getElementById("password")
.setCustomValidity('Please enter a password');
};
};
function deleteBadConfirm() {
$("#confirmpassword").prop("value", "");
};
//Added this to show setCustomValidity message/tooltip without submit event
function runReportValidity() {
document.getElementById("password").reportValidity();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password" style="text-align:center;" type="text" name="password" tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required oninvalid="valid_pass()" oninput="this.setCustomValidity('')" onkeyup="deleteBadConfirm(); valid_pass();" />
<!-- Added this to show setCustomValidity message/tooltip without submit event -->
<input type="button" onClick="runReportValidity()" value="Report Validity">
Upvotes: 1
Reputation: 5622
You have a error in below line Change this
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don't use any symbols');
To
document.getElementById("password")
.setCustomValidity('At least, enter 6 characters; Don\'t use any symbols');
by adding a escape character - backslash ()
Upvotes: 1