Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

jquery - Set input as invalid

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...