简体   繁体   中英

Validate and allow specific username to login in username text field of HTML

I want to allow only two selected users to login to my application on-click of submit button . These two usernames are listed in a text file called as user.txt so, the username parameter should be read and if the username entered in the text field matches the entries of the user.txt file then the user must be allowed to login else error should be displayed.

Note: The challenge here I already have one validation( validateForm()) which is working fine on click of the submit button. It checks to ensure the username and password fields are not empty. I need this new specific username allow validation validation as well on-click of submit button.

Can someone suggest me example codes how can I handle this validation using Ajax or jQuery or simple JavaScript?

Username.txt file

Username1 : Tom
Username2 : Harry

Check whether username and password text fields are not empty:

function validateForm() {
    var x = document.forms["login"]["userid"].value;
    if (x == null || x == "") {
        alert("Username is empty");
        return false;
    }
    var x = document.forms["login"]["pswrd"].value;
    if (x == null || x == "") {
        alert("Password is empty");
        return false;
    }
}

You need to check against the server, where the file.txt is located (btw: databases are used for that purpose, usually).

The only way to do it on client side (javascript), is to have the list of names inside an array - but that doesn't make sense - as the client would be able to see the array. So you really should use server side for that purpose.

Have a look at tutorials like this one if you want proper (secure) authentication.

If you only want to check against the usernames, try this jQuery code:

$.ajax({
    type: "POST",
    url: "script_url",
    dataType: "json",
    data: {
        user : $("#user").val(),
        call : "checkUser"  
    },
    beforeSend: function(){ },
    success : function(response){
        if(!response){
            alert('User not allowed!');
        }
    },
    complete: function(){ }
})

And PHP code:

$lines = file('../location/Username.txt');
$arr_users = array();
foreach($lines as $line){
    $arr = explode(':', $line);
    $arr_users[] = trim($arr[1]);
}

function checkUser($request){
    return in_array($request['user']);
}

if (!empty($_POST['call'])) { 
    die($_POST['call']($_POST));
}

Best regards!

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