Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...