简体   繁体   中英

How to check if a username is already taken?

I need to check the username input in a registration form using javascript along with flask in python but I don't know how to implement it.

I have to use $.get in the javascript part and in the python code which should check and return a jsonifyied true or false.

Python code:

@app.route("/check", methods=["GET"])
def check():
    """Return true if username available, else false, in JSON format"""
username = request.args.get("q")
rows = db.execute("SELECT * FROM users WHERE username = :username", username=username)
if len(rows) >= 1 or len(username) < 1:
    return jsonify(False)
else:
    return jsonify(True)

HTML part:

<form action="/register" method="post" id ="register">
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
        </div>
        <div class="form-group">
            <input class="form-control" name="password" placeholder="Password" type="password">
        </div>
        <div class="form-group">
            <input class="form-control" name="confirmation" placeholder="Confirm Password" type="password">
        </div>
        <button class="btn btn-primary" id="submittion" type="submit">Register</button>
    </form>
    <script>
       let input = document.querySelector('input[name=username]');
       input.onkeyup = function() {
            $.get('/check?q=' + input.value, function(data) {
                if (data == "FALSE"){
                    data.preventDefault()
                    alert("Username is not available!");
                }
            });
        };
    </script>

It should alert the user if the username already exists once it is checked in the SQL. The debug shows it does search through the list for the username but it doesn't alert or anything.

You are returning a true/false value. In JavaScript this value will not be a string in which you are testing against:

if (data == "FALSE")

By testing against an actual boolean, you should get your desired result:

if (data == false)

or

if (!data)

I guess you should write it as following:

@app.route("/check", methods=["GET"])
def check(username):
    """Return true if username available, else false, in JSON format"""
username = request.args.get("q")
rows = db.execute("SELECT * FROM users WHERE username = :username", username=username)
if len(username) < 1:
    return jsonify(False), 400
if len(rows) < 1:
    return jsonify(False), 400
else:
    return jsonify(True), 200

and in javascript:

if (data == "FALSE")

to

if (data[1] == false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM