Prevent user from registering if username is taken - javascript

So my script perfectly checks whether username is free or not but regardless of that when user submits all forms he is able to register. I need a way to prevent user from registering if username is taken. Here is the code:
index.php
$("#username").keyup(function(){
var val=$("#username").val();
$("#address").html("Your address will be askfolio.com/" + val);
$("#freeu").html("<img src='css/ajax-loader.gif' style='margin-left:-75px;'>");
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:$("#username"),
success:function(data){
if (data == 1){
$("#freeu").html("<img src='css/accept.png' style='float:left;padding-right:65px;'>");
$("#reg-error").css("display","none");
}else{
$("#freeu").html('');
$("#reg-error").css("display","block");
$("#reg-error").html('Username is already taken, try another.');
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
});
function Users_Registration()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $("#name").val();
var lastname=$("#lastname").val();
var username = $("#username").val();
var remail = $("#remail").val();
var rpass = $("#rpass").val();
var day=$("#day").val();
var month=$("#month").val();
var year=$("#year").val();
if(name == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your name in the required field.');
$("#name").focus();
}
else if(lastname == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html(' Please enter your Last Name in the required field.');
$("#lastname").focus();
}
else if(username == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your desired username to proceed.');
$("#username").focus();
}
else if(remail == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your email address to proceed.');
$("#remail").focus();
}
else if(reg.test(remail) == false)
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid email address to proceed.');
$("#remail").focus();
}else if (rpass == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid password to proceed.');
$("#rpass").focus();
}
else if (day == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a day to proceed.');
$("#day").focus();
}else if (month == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a month to proceed.');
$("#month").focus();
}else if (year == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a year to proceed.');
$("#year").focus();
}
else
{
var dataString = 'name='+ name + '&lastname='+ lastname + '&username='+ username + '&rpass='+ rpass + '&remail='+ remail + '&year=' + year + '&month=' + month + '&day=' + day +'&page=signup';
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#reg-error").html('<br clear="all"><div style="padding-left:115px;"><font style="font-family:Verdana, Geneva, sans-serif; font-size:12px; color:black;">Please wait</font> <img src="images/loadings.gif" alt="Loading...." align="absmiddle" title="Loading...."/></div><br clear="all">');
},
success: function(response)
{
$("#reg-error").html("Loading");
var username="<?php echo $loguser; ?>";
window.location=username;
}
});
}
}
ufree.php
<?php
include "db.php";
if (isset($_POST['username'])) {
$username=$_POST['username'];
$sql=mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($sql) == 0) {
echo "1";
}else {
echo "<div style='padding-top:4px;'>username is taken</div>";
}
}
?>

Apart from the SQL Injection vulnerability that you have in your sql queries, your approach to username check is somewhat redundant. By checking the username upon every character input you add extra load to the browser and to your server.
I suggest you combine the two processes in one step meaning you do the username check and register in the same place. In your Register.php file check the username availability right before the registration and if the username is taken display a proper message and if not do the registration.

Goes without saying but regardless of the javascript validation, your server still needs to be checking that the username is available at point of registering, since anyone can disable or manipulate the javascript.
Also as Hamed states, your php code is highly vulnerable. At the very least, you should use the following prior to using it in your sql:
$username = mysql_real_escape_string( $_POST[ 'username' ] );
That said, for usability, what you need to do is add an onsubmit function to your form, which checks if the username is valid or not prior to submitting. (summarised your code for simplicity)
var validUser = false;
$("#username").keyup(function(){
var val=$("#username").val();
validUser = false;
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:val,
success:function(data){
if (data == 1){
validUser = true;
}else{
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
function formsubmit()
{
if( !validUser )
{
alert( 'Username is already taken, try another' );
return false;
}
return true;
}
Then in your form:
<form action="whatever" onsubmit="return formsubmit();">
...
</form>

Once of my favorite jQuery plugin is the validation eng.
https://github.com/posabsolute/jQuery-Validation-Engine
It has very nice validation for doing just what you are looking for. It does all kinds of fields including inline ajax for username check. If the response from ajax call is not true, then the form won't submit. I use it for my signup forms. Once the user goes to the next field it validates, if it doesn't pass i.e. the username is not available, it will say username not available in red. The form won't submit.
It's not hard to setup. Here is a demo of the ajax. Note it won't actually validate on this demo site but it's an example. You can see how it won't submit though if it's blank or not validated. It's very customizable.
http://www.position-relative.net/creation/formValidator/demos/demoAjaxSubmitPHP.html
Oh course take care of any mysql security issues and check to make sure dupes can't be entered into the database as well.

Related

Clearing specific fields (not all) when a form is submitted

Im trying to clear only the password and confirm password fields when those are not matched.
Im calling a function when the submit button is pressed which contains a password checking condition. How should I clear only password and confirmpassword inputs if that condition is true?
function checkmatch()
{
var name = $("#username").val();
var address = $("#address").val();
var email = $("#emailid").val();
var mobile = $("#phonenum").val();
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
return false;
}
else if((name==null || name == "") || (address==null || address == "") || (email==null || email == "") || (mobile=null || mobile == "") || (password==null || password == "") || (cnfirmPassword==null || cnfirmPassword == ""))
{
alert("Please fill all the required fields.");
return false;
}
else
{
$.ajax(
{
type: "POST",
url: "assmt1.php",
datatype: "html",
data: $("#fm1").serialize(),
success: function(response)
{
}
});
alert("Your form has been submitted. Thank you!");
}
}
Is this what you mean?
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
$("#newPwd").val('').focus(); ///this will not focus because of alert
$("#confirmPwd").val('');
return false;
}
All you need to do is call the same function you used to get the value.
Just pass empty string to val() like so:
$("#newPwd").val('');
$("#confirmPwd").val('');

Javascript post to check username availability not working

Im trying to check if the register username's available but everytime the clientside returns that the username its available.
This is my clientside code:
$(document).ready(function()
{
$("#register_username").blur(function(){
var user = $("#register_username").val();
$.post("register",
{
username: user
},
function(data, status){
if(data == '1')
{
alert('Good, username its available!');
}
else
{
alert('Snap!You cant use this username :(!');
}
});
});
});
And this is the serverside code:
if(strlen($_POST['username']) > 0)
{
$usr = $_POST['username'];
if($usr == 'test')
echo '1';
else
echo '2';
}
PHP Version: 5.5
first of all, i guess if the input field has value "test" it would say "you cannot use this username"?
in your code if input is "test" ($usr == "test" - that comes from input) you echo 1, and in your code 1 means username is available? So shouldn't it be backwards?
Does it say "username is available" with every input?

JavaScript redirection error

I am trying to use JavaScript to redirect to a PHP page on my site, however, when I do it, nothing happens, apart from the alert boxes if I do not fill in the parameters. Is there something I am doing wrong?
document.getElementById("submit").onclick = check;
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
}
Your default form action takes place overriding your redirect. Return false from the handler to prevent it from taking place:
function check()
{
if(document.getElementById("name").value == "")
alert("The field 'Name' is required.");
else if (document.getElementById("message").value == "")
alert("The field 'Message' is required");
else
window.location.href = "scripts/main/contact.php?msg=" + document.getElementById("message").value;
return false; // <------ here
}

replace span text (error) after retyping vars jquery javascript

Whats the best approach for jquery realtime validation checking?
Onsubmit the span with each label gets changed to for example:
enter your email | submit | email is not correct
but when you change the value again you have to submit again to remove the email is not correct message.
So im searching for a "realtime" error handling or something. What is the best approach to do this considering my code?
<script type="text/javascript">
$(document).ready(function()
{
$('form #status').hide();
$('#submit').click(function(e) {
e.preventDefault();
var valid = '';
var required = 'is required';
var name = $('form #name').val();
var subject = $('form #subject').val();
var email = $('form #email').val();
var message = $('form #message').val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//error checking
if (name == '' || name.length <= 2)
{
valid = '<p>your name' + required + '</p>';
$('form #nameInfo').text('Name can not contain 2 characters or less!');
}
if(!filter.test(email)){
valid += '<p>Your email'+ required +'</p>';
$('form #emailInfo').text('Email addres is not valid');
}
if (message == '' || message.length <= 5)
{
valid += '<p>A message' + required +'</p>';
$('form #messageInfo').text('Message must be over 20 chars');
}
if (valid != '')
{
$('form #status').removeClass().addClass('error')
.html('<strong>Please correct errors belown </strong>' + valid).fadeIn('fast')
}
else
{
$('form #status').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
</script>
I'm not 100% sure I understand the question. Do you want to reset #emailInfo text when user corrects the input? If so, you can use either onchange, onkeypres or on focus events:
$("#email").change(function(){
$("#nameInfo").text("Enter your email");
});
Better yet, you can do your validation on corresponding field change rather than on form submit.
The following example will validate email field on each key pressed:
$("#email").keypress(function(){
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email = $('#email').val();
if(!filter.test(email)){
$('#emailInfo').text('Email addres is not valid');
} else {
$('#emailInfo').text('');
}
});
You can validate other fields in a similar way. Or you can use jQuery Validation plugin.

Can I wait for $.get() call before submitting the form?

I have a sign-up form which prompts for the first name, last name, username, password and e-mail address. I'm using two separate $.get() methods to check if the username and e-mail address are not existing.
This is my function:
function validateSignUp() {
var firstName = $("#first-name").val();
var lastName = $("#last-name").val();
var username = $("#username").val();
var password = $("#pass").val();
var email = $("#email").val();
var passwordVerifier = $("#retype-pass").val();
var emailVerifier = $("#retype-email").val();
errorMessage = "";
var isUsernameValid = validateUsername(username);
var isError = false;
// validate first name field
if (firstName == "" || lastName == "") {
isError = true;
$("#error-message").html("All fields are required");
}
// validate password
if (validatePassword(password) == false) {
isError = true;
$("#check-password").html("Password is invalid");
}
else {
$("#check-password").html("");
}
// validate password verifier
if (passwordVerifier == password) {
if (validatePassword(passwordVerifier) == false) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters");
}
else {
if (password != passwordVerifier) {
isError = true;
$("#recheck-password").html("Minimum of 6 characters and maximum of 30 characters ");
}
else {
$("#recheck-password").html("");
}
}
}
else {
isError = true;
$("#recheck-password").html("Passwords didn't match");
}
// validate username field
if (isUsernameValid == false) {
isError = true;
$("#check-username").html("Alphanumeric characters only");
} // if
else if (isUsernameValid == true) {
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
} // else
// validate e-mail address field
if (validateEmail(email) == false) {
isError = true;
$("#check-email").html("Sorry, the e-mail you typed is invalid");
} // if
else if (validateEmail(email) == true) {
$.get("/account/checkavailabilitybyemail", { email: email },
function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
}
else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
});
}
if (isError == true) {
return false;
}
return true;
}
When other fields are blank and the username and/or e-mail address is existing, the form is not submitted. And the callback functions of the get methods are called as well. But when I'm going to submit my form with no empty fields, it is automatically submitted without checking the username and/or e-mail by $.get(). Is there anything wrong with my function or I'm not yet discovering something. Thanks.
You need to use a full ajax() call and set the async property to false. This makes your request synchronous, i.e. it forces the browser to wait until doing anything else. Try this:
$.ajax({
url: "/account/checkavailabilitybyemail",
data: { email: email },
async: false,
success: function(data) {
if (data == "Not Existing") {
$("#check-email").html("");
} else if (data == email) {
isError = true;
$("#check-email").html("Sorry, this e-mail is already registered");
}
})
});
if (isError == true) {
return false;
}
I suggest you leverage Jquery validate with two remote rules. It's quite easy to implement and a very mature plugin. This way you can focus on other aspects of your UX and not have to re implement this validation logic should you need to validate another form in your project.
Inside your main function, you cannot directly wait for the $.get() to return. But you can move the form submission to the success callback of the AJAX call (assuming form to contain a reference to the actual form element):
$.get("/account/checkavailabilitybyusername", { username: username },
function(data) {
if (data == "Not Existing") {
$("#check-username").html("");
form.submit();
//--------------------------^
}
else if (data == username) {
isError = true;
$("#check-username").html("Sorry, this username is already registered");
}
}
);
Note however, that then the form submission depends on the AJAX to return. Most useful would be a timeout (with window.setTimeout()) and a server-side validation, if the JS doesn't respond or the user has JS disabled.

Categories

Resources