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;
}
}
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!