This question already has an answer here:
Why doesn't my equality comparison using = (a single equals) work correctly? [duplicate]
(1 answer)
Closed 5 years ago.
I'm trying to build a form that will check (live) to see whether a person has mismatched a string when entered into text fields. The practice is a user entering data into a password form.
HTML Below:
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" value="" placeholder="Password" onKeyUp="checkPasswordStrength();">
</div>
<div class="form-group">
<input type="password" name="vPass" id="cpassword" class="form-control" value="" placeholder="Password">
<span id="output"></span>
</div>
And below is the jQuery used:
<script type ="text/javascript">
$("#cpassword").blur(function checkPassMatch(){
var originEmpt = $("#password").text(""); // Checking if input is empty
var origin = $("#password").text(); // Password
var conf = $("#cpassword").text(); // Confirm password
if (origin != conf){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else {
$("#output").html("");
}
if (originEmpt){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
$("#output").html("");
}
})
</script>
Through debugging, if I totally remove the first if else statement from the jQuery, I can receive the $("output").html(); as desired.
I have tried for both input fields:
$("#password").text() / .val(); / .html(); / .innerHTML();
But the code still fails to check whether one input field matches another. Any ideas why?
Cause your second checks output overrides the first one. You need to nest it:
if (origin != conf){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else if (!originEmpt){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
$("#output").html("");
}
Related
This question already has an answer here:
AngularJS update input manually does not trigger change in the model
(1 answer)
Closed 3 years ago.
Here is the following code;
<div class="col-xs-12 col-sm-9">
<input id="Shipping_FirstName" name="firstname" ng-model="userOrder.Shipping.FirstName" type="text" class="form-control nsg-form--input ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength" ng-class="{'is-invalid': shipping_subform.$submitted && shipping_subform.firstname.$invalid}" required="" maxlength="35" tooltip="Please enter your first name" tooltip-toggle="shipping_subform.$submitted===true && shipping_subform.firstname.$invalid===true" esw-google-analytics-blur=""> <!-- ngIf: shipping_subform.$submitted && shipping_subform.firstname.$invalid -->
</div>
I have tried the following which writes the text to the input field;
document.getElementById("Shipping_FirstName").value = "test"
document.querySelector("input[id='Shipping_FirstName']").value = "test";
However, when I press the submit button, it says "Please enter your first name" as if the code above actually didn't write the text.
How can I fix this?
Thanks for any help, it's all appreciated.
Thanks to epascarello, the answer is;
var e = document.getElementById("Shipping_FirstName");
e.value = "test";
var $e = angular.element(e);
$e.triggerHandler('input');
I'm using a small script to validate a postcode, which works and stops the user entering an invalid password, but when an invalid post code is entered you then can't submit a correct entry. For example, if I enter 'ST' I get the message telling me the postcode is invalid, so without refreshing the page manually I enter 'ST6 1SA' (which is a valid Stoke postcode) and I can't submit the form, I just keep getting the invalid tool tip advising me the post code is not in the correct format.
JS:
<script>
// Validate the postcode before it's sent
(function () {
var postcode = document.getElementById('postcode-entry');
var wrapper = document.getElementById('validation');
var notify = document.createElement('div');
var mnisLookup = document.getElementById('mnis-results');
var matchingClients = document.getElementById('matching-clients');
var postcodeWrapper = document.getElementById('postcode-wrapper');
notify.id = 'notify';
notify.style.display = 'none';
wrapper.appendChild(notify);
postcode.addEventListener('invalid', function (event) {
if (!event.target.validity.valid) {
notify.textContent = 'Please enter a valid postcode e.g. ST1, ST1 4BJ';
notify.className = 'error';
notify.style.display = 'block';
postcode.className = 'form-control invalid';
}
});
})();
</script>
HTML:
<form id="postcode-wrapper" class="form-horizontal">
<div id="postcode-lookup" class="form-group">
<label for="postcode-entry" class="col-sm-1">Postcode:</label>
<div id="postcode-entry-wrapper" class="col-sm-3">
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" />
</div>
<div class="col-sm-1">
<input id="search" type="submit" value="Search" class="btn btn-default" />
</div>
<div id="validation" class="col-sm-7"></div>
</div>
</form>
Just a quick note that may affect how the page is refreshing, this is inside an MVC Razor page and wrapped with Html.BeginForm - not sure if that makes a difference?
While debugging your code, i found that the event.target.validity.valid was returning false even if the input was valid e.g. 'ST6 1SA'. This was occuring because it does not update the custom validation for the new input and the previous state persists even after entering the valid input.
So to update and reset the previous validation, you have to reset setCustomValidity('') on input change, i.e. oninput="setCustomValidity('')"
Please replace this code:
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" oninput="setCustomValidity('')"/>
I'm looking to create an HTML5 custom validation message when I enter 2 passwords which don't match.
Here's my HTML and JQuery
HTML:
<form class="form-group main-settings-form" id="main-settings-form-password">
<input class="form-control main-settings-form-input password-main" type="password" placeholder="Enter new password" id="new-password" pattern='(?=.*\d)(.{6,})' required>
<input class="form-control main-settings-form-input" type="password" placeholder="Retype new password" id="confirm-password" pattern='(?=.*\d)(.{6,})' required>
<div class="main-settings-form-buttons">
<button type="button" class="btn btn-danger settings-edit-cancel">Cancel</button>
<button class="btn btn-success" type="submit">Save</button>
<br>
<br>
Forgot password?
</div>
</form>
JS:
$(document).ready(function () { //This confirms if the 2 passwords match
$('#confirm-password').on('keyup', function (e) {
var pwd1 = $("#new-password").get(0);
var pwd2 = $("#confirm-password").get(0);
pwd2.setCustomValidity("");
if (pwd1 != pwd2) {
document.getElementById("confirm-password").setCustomValidity("The passwords don't match"); //The document.getElementById("cnfrm-pw") selects the id, not the value
}
else {
document.getElementById("confirm-password").setCustomValidity("");
//empty string means no validation error
}
e.preventDefault(); //would still work if this wasn't present
});
});
The problem is, the message is always triggered even if the passwords do match. Please help me trigger the message only when the passwords dont match, and be allowed to safely submit when they do.
JS fiddle: https://jsfiddle.net/kesh92/a8y9nkqa/
password requirements in the fiddle: 6 characters with atleast one number
jQuery get() returns the dom elements of each...they can never be equal
You want to compare values.
Try changing
if (pwd1 != pwd2) { //compare 2 dom nodes
To
if ( pwd1.value != pwd2.value) { //compare 2 dom node values
Note however that you also need to now consider empty values since you are over riding validty
I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.
My Name:<input class="clr" id="name" type="text" /><span class="clr" id="name_error">Name is required</span> <br /><br />
My Email Adress:<input class="clr" id="email" type="text" /><span class="clr" id="email_error">Email is required</span> <br /><br />
My Organisation Name:<input class="clr" id="organisation" type="text" /><span class="clr" id="org_error">Organisation is required</span> <br /><br />
I have 3 input fields. I'm using span to display error message when submitting empty fields.
My problem is, if name field is empty, we should get "Name is required" error, if email field is empty, we should get "email is required" error and so on.
For this, I'm writing below code.
if (name == "")
$("#name_error").show();
else
$("#name_error").hide();
if (email == "")
$("#email_error").show();
else
$("#email_error").hide();
if (organisation == "")
$("#org_error").show();
else
$("#org_error").hide();
Is there any way to reduce if/else statements?
Using jQuery effectively, you can do this way.
$('input.clr').each(function(){
if ($(this).val() == "")
$(this).next('span.clr').show();
});
Before that, we need to hide them this way:
$('span.clr').hide();
You could do this :
var obj = window; // or something else, depending on your scope
['name', 'email', 'organisation'].forEach(function(v) {
var $e = $('#'+v+'_error');
if (obj[v]=="") $e.show();
else $e.hide();
});
Note that
this supposes a little more strictness, with the replacement of "org" by "organisation"
I tried to mimic your code but changing at the root (i.e. where you fill the variables like name) would allow for a simpler code
if you know the DOM doesn't change and the error span always follows the input, Praveen's answer is probably simpler and suited