I have two inputs, e.g.
pass: <input type="password" name="pass" required/> pass again: <input type="password" name="pass2" required/>
and I want to compare these inputs, and if they match, set input as valid. I tried this, but I think that prop('valid', true);
does not work:
$(document).ready(function() { $('input[name=pass2]').keyup(function() { if($('input[name=pass]').val() == $('input[name=pass2]').val()) { $('#pass_hint').empty(); $('#pass_hint').html('match'); $(this).prop('valid', true); } else { $('#pass_hint').empty(); $('#pass_hint').html('mismatch'); $(this).prop('invalid', true); } }); });
I create a registration form and if passwords are not the same, input field is invalid and I can´t submit this and show me some hint. ...and I don´t know how I set this input as invalid
setCustomValidity("Invalid field."); will make the field invalid. field. setCustomValidity(""); will make the field valid unless it fails an HTML5 constraint. Also, if you want the browser's validity message to show up on input or blur you can use field.
The Invalid JavaScript error is issued in the following situations: JavaScript '<JavaScript node>' has syntax errors. The JavaScript node has one or more syntax errors. Double-click the JavaScript node and correct the lines that have syntax errors.
To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.
The :invalid selector selects form elements with a value that does not validate according to the element's settings.
In the HTMLInputElement interface, there is no such property as valid
or invalid
.
You can use the setCustomValidity(error)
method with native form validation.
As for your script, here's a demo that should work in all HTML5 compliant browsers:
$('input[name=pass2]').keyup(function () { 'use strict'; if ($('input[name=pass]').val() === $(this).val()) { $('#pass_hint').html('match'); this.setCustomValidity(''); } else { $('#pass_hint').html('mismatch'); this.setCustomValidity('Passwords must match'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action='#'> <p>Password: <input name=pass type=password required> </p> <p>Verify: <input name=pass2 type=password required> </p> <p id=pass_hint></p> <button type=submit>Submit</button> </form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With