Username taken check with jquery validate plugin - php

I am trying to use the username taken or not using jquery validate plugin. but dosent seems to work. I would like to know where I went wrong, all other validation works fine. except for this.
jquery validate plugin page: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
javascript
<script type="text/javascript">
$(document).ready(function(){
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 2,
remote: "users.php"
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
},
email: "A valid email will help us get in touch with you.",
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('adduser.php', $("#register").serialize(), function(data) {
$("#register").fadeOut('fast', function(){
$('#results').html(data);
});
});
}
});
});
</script>
users.php
<?php
$request = $_REQUEST['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>
register.php
<form name="register" id="register" method="post" action="">
<section>
<label for="username">Username:</label>
<div>
<input type="text" tabindex="1" class="input" id="username" name="username" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="email">email</label>
<div>
<input type="text" tabindex="2" class="input" id="email" name="email" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="password">Password</label>
<div>
<input type="password" tabindex="3" class="input" id="password" name="password" value=""/>
</div>
</section>
<!--#-->
<section>
<label for="confirm_password">Confirm Password</label>
<div>
<input type="password" tabindex="4" class="input" id="confirm_password" name="confirm_password" value=""/>
</div>
</section>
<!--#-->
<br/>
<input type="submit" tabindex="5" id="submit" value="REGISTER" />
</form>
<div id="results"> </div>
thanks in advance.

I have the same but I use their validation and this to check if username exists. It works great.
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'username must have atleast 3 characters';
var checking_html = 'searching...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("checkuser.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html('<span class="is_available"><b>' +username + '</b> is available</span>');
//this is the id of my save button it'll display if available
$('#newacct').css("display", "inline");
}else{
//show that the username is NOT available
$('#username_availability_result').html('<span class="is_not_available"><b>' +username + '</b> is not available</span>');
}
});
}
</script>

First, you have an extra } that is closing your messages option prematurely, leading to the remaining messages being ignored. You should move this } after the confirm_password message block. Second, you should be calling jQuery.validator.format rather than jQuery.format. I believe this is why this particular validation rule doesn't work. Correct these and see if it works for you.

To answer the OP, you might want to use $_GET. Also, mysql_num_rows has been deprecated as of PHP 5.5.0, so you'll probably want to update that. You could just check if the query returns false.
<?php
$request = $_GET['username'];
//usleep(150000);
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
?>

Try this......
JS
$("#register").validate({
debug: false,
rules: {
username: {
required: true,
minlength: 6,
remote: {
url: "Your PHP",
type: "post",
data: {
funct: 'user_check',
username: function() {
return $( "#username" ).val();
}
}
}
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters",
remote: jQuery.format("{0} is already in use")
}
});
});
PHP
<?php
function user_check(){
$username = $_POST['username'];
$query = mysql_query("SELECT * FROM users WHERE username ='$username'");
if ($query == false){
$valid = 'true';} // username available
else{
$valid = 'false'; // username unavailable
}
echo $valid;
}
?>
May help..

Related

jQuery Validation - Remote function with additional data

I am having issues with validating some data.
I want to check if someone has reviewed a company before by checking for the company_id and the logged in users account_number in my reviews table.
The code I currently has doesn't ever seem to find anything in the reviews table so doesn't warn people they can't submit another review.
Your help to get this working is much appreciated.
Here is the code I have so far:
Form
<form name="review" id="review" method="post" action="/db_processing/reviews/process-reviews.php">
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
<input type="hidden" value="<?php echo($_SESSION["ID"]) ?>" name="account_number" />
<p class="cs-threequarter">
<b>Comments:</b><br>
<textarea name="comments" style="width:95%; height: 150px"></textarea>
</p>
<p class="cs-quarter">
<b>Rating:</b>
<span class="star-rating">
<input type="radio" name="rating" value="1"><i></i>
<input type="radio" name="rating" value="2"><i></i>
<input type="radio" name="rating" value="3"><i></i>
<input type="radio" name="rating" value="4"><i></i>
<input type="radio" name="rating" value="5"><i></i>
</span>
</p>
<p><input class="cs-btn cs-red" name="submit" type="submit" value="Submit Review!"></p>
<div class="cs-container"></div>
<div class="cs-error-note" id="cs-error-note3"></div>
</form>
<script src="/js/validation/reviewval.js"></script>
jQuery Validation Script
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li",
ignore: "not:hidden",
rules: {
comments: {
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, }
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
Check-account.php
<?php
require('../../../private_html/db_connection/connection.php');
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
if(isset($_POST['account_number'])) {
$account_number = $_POST['account_number'];
$compid = $_POST['company_id'];
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number =$account_number && company_id =$compid");
$query->execute();
$rows = $query->fetchAll();
$total_rows = count($rows);
if( $total_rows > 0 ){
echo 'false';
} else {
echo 'true';
}
}
?>
Validation code working fine, there is no problem expect unnecessary comma ,. remove it, Not all browsers are very forgiving.
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li"
ignore: "not:hidden",
rules: {
comments:
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, //<-----Remove this, it's unnecessary
}
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
HTML
The problem is here, because of it validation and query both failing.
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
assign id to this input because you are fetching it's value with id selector in validation script here return $("#company_id").val(); so it will be
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" id="company_id" />
last in PHP
put quotes ' around variables inside query, rest is all good and working.
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number = '$account_number' && company_id = '$compid'");

Insert data into database after jQuery validation. Button only works for validation [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I would like to insert the data into my database after jquery validation. However, the submit button only works for the validation and it won't submit data. Please help me thanks~
This is my form
<form id="myform" method="POST">
<label for="username">Username: </label>
<input type="text" class="left" id="username" name="username">
<label for="name">Name: </label>
<input type="text" class="left" id="name" name="name">
<label for="password">Password </label>
<input type="password" class="left" id="password" name="password">
<label for="repassword">Password </label>
<input type="password" class="left" id="repassword" name="repassword">
<label for="email">Email </label>
<input type="email" class="left" id="email" name="email">
<label for="contact">Contact</label>
<input type="text" class="contact" id="contact" name="contact">
<input id="submit" type="submit" name="submit" value="Send" />
</form>
This is my jquery validation form
<script>
$.validator.addMethod('contact', function (value, element) {
return this.optional(element) || /^\d{3}-\d{7}$/.test(value);
}, "Please enter a valid phone number");
jQuery.validator.addMethod( 'passwordMatch', function(value, element) {
// The two password inputs
var password = $("#password").val();
var confirmPassword = $("#repassword").val();
// Check for equality with the password inputs
if (password != confirmPassword ) {
return false;
} else {
return true;
}
}, "Your Passwords Must Match");
$(document).ready(function() {
$( "#myform" ).validate({
rules: {
debug:false,
username: {
required: true,
rangelength:[4,10],
// remote: "user_check2.php"
},
name: {
required: true,
rangelength:[4,10]
},
password: {
required: true,
rangelength:[6,10]
},
repassword: {
passwordMatch: true // set this on the field you're trying to match
},
email: {
required: true,
},
contact: {
required: true,
},
},
messages: {
username: {
//remote:"Username already existed",
required:"Enter your username",
},
name: {
required:"Please enter your name",
},
password: {
required:"Please enter your Password",
rangelength:"You must contain 6 to 10 character"
},
contact: {
required:"Please enter your phone number",
},
});
});
</script>
The last step is to insert the data into the table in database. However the submit button does not work.
<?php
if(isset($_POST['submit']))
{
$adminusername = $_POST["username"];
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["contact"];
$password = $_POST["password"];
//$query = "select * from admin where Admin_Username = '$adminusername'";
//$result = mysqli_query($conn,$query);
//$rowcount = mysqli_num_rows($result);
mysqli_query($conn,"Insert into admin(Admin_Username,Admin_Name,Admin_Email,Admin_Contact,Admin_Password) values
('$adminusername','$name','$email','$phone','$password')");
mysqli_close($conn);
}
?>
I think you miss action attribute in your form.
<form method="post" action="your_php_code.php">

how can I check username exists in db via a jquery keyup

Hi I'm creating a form that contains username password etc.. and I used jquery to validate the form and I want to check that the username is already present in the mysql database. if it is present then the form should not be submitted.
Here is my code so far:
<form id="register" name="register" action="somewhere.php" method="post" >
<label for ="Username"> Username </label><br>
<input type="text" class="register-control" id="Username" name="Username" autocomplete="off" placeholder="Enter Username"> <br>
<div class="username_avail_result" id="username_avail_result"></div><br>
<label for ="Password"> Password </label><br>
<input type="password" class="register-control" id="password" name="password" placeholder="Enter Password" ><br><br>
<label for ="Confirm-Password"> Confirm Password </label><br>
<input type="password" class="register-control" id="Confirm_Password" name="Confirm_Password" placeholder="Confirm Password" ><br>
<label for="email" > Email </label><br>
<input type ="email" class="register-control" id="email" name="email" placeholder="Enter Valid Email"><br><br>
<button type="submit" >Submit</button>
</form>
And the jquery is:
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#Username').keyup(function(){ // Keyup function for check the user action in input
var Username = $(this).val(); // Get the username textbox using $(this) or you can use directly $('#username')
var UsernameAvailResult = $('#username_avail_result'); // Get the ID of the result where we gonna display the results
if(Username.length > 2) { // check if greater than 2 (minimum 3)
UsernameAvailResult.html('Loading..'); // Preloader, use can use loading animation here
var UrlToPass = 'action=username_availability&username='+Username;
$.ajax({ // Send the username val to another checker.php using Ajax in POST menthod
type : 'POST',
data : UrlToPass,
url : 'checker.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
UsernameAvailResult.html('<span class="success">Number available</span>');
}
else if(responseText > 0){
UsernameAvailResult.html('<span class="error">Number already taken</span>');
}
else{
alert('Problem with sql query');
}
}
});
}
});
$("#register").validate({
errorElement: 'div',
rules:{
"Username":{
required: true,
minlength:5
},
"password":{
required:true,
minlength:5
},
"Confirm_Password":{
required:true,
equalTo: "#password"
},
"email":{
required:true,
}
},
messages: {
Username:{
required: "Please provide a username",
minlength: "Your Username must be at least 5 characters long"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
Confirm_Password: {
required: "Please provide a confirm password",
equalTo: "Please enter the same password as above"
}
},
email:{
required: "Please provide a valid email",
}
});
});
</script>
Both work super, my doubt is how can I merge both, and also if the username is already taken the form should not submitted.
run a query in your php file to get all users with the current email i.e."example#example.com" and username i.e. "example" if you get any rows then it exists therefore don't add it, otherwise, add it!
$_GET['email'] = $email;
$result = mysql_query("SELECT * FROM users WHERE email='$email'");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
if(mysql_num_rows($result) >= 1) {
//show already registered
//you can either return false or change the return string/array to "registered"
} else {
mysql_query('INSERT INTO users ..............);
}
You could clear the username if its taken, thus causing the validation to fail
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
UsernameAvailResult.html('<span class="success">Number available</span>');
}
else if(responseText > 0){
UsernameAvailResult.html('<span class="error">Number already taken</span>');
//clear username
$('#Username').val('');
}
else{
alert('Problem with sql query');
//clear username
$('#Username').val('');
}
}
});
You can check the username on Keyup and form submit and prevent the form submit when username exists.
$("#register").submit(function( event ) {
if(usernameExists($('#Username').val()))
event.preventDefault();
});
$('#Username').keyup(function(){
usernameExists($(this).val();
});
usernameExists() should have all your current validation and ajax code as in your $('#Username').keyup(function(){ });

jQuery remote validation always returning false

I have the below code for implementing a very basic login system on my site (using jQuery Mobile). The problem is that, when submitting the form through jQuery Mobile (and therefore using the validator), the validator always returns false and throws an error, even if the password is correct. When I wrote a separate form with nothing other than the two textboxes and a submit button and ran it directly to the validation script, it returned the correct value of true or false depending on the given password. What's wrong with the jQuery script that causes it to always return false?
HTML/JS:
<form action="logins.php" method="POST" id="loginForm" name="loginForm" data-ajax="false">
<label for="email" class="ui-hidden-accessible">Email Address:</label>
<input type="text" id="email" name="email" value="" placeholder="Email Address" />
<label for="pass" class="ui-hidden-accessible">Password:</label>
<input type="password" id="pass" name="pass" value="" placeholder="Password" />
<input class="submit" data-role="submit" type="submit" value="Submit" />
</form><br>
<br>
Return to home page
<script>
$('#login').bind('pageinit', function(event) {
$('#loginForm').validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
email: {
required: true,
email: true
},
pass: {
required: true,
remote: {
url: "passcheck.php",
type: "post"
}
}
},
messages: {
email: {
required: "You must enter an email address.",
email: "You must enter a valid email address."
},
pass: {
required: "You must enter a password.",
remote: "Your username/password combination is incorrect."
}
}
});
});
</script>
PHP (passcheck.php):
<?php
require("common.php");
$query = "SELECT password FROM users WHERE email = :email";
$query_params = array(':email' => $_POST['email']);
try {
$stmt = $conn->prepare($query);
$stmt->execute($query_params);
} catch(PDOException $ex) {
die("Failed to run query.");
}
$hash = $stmt->fetchColumn();
if(crypt($_POST['pass'], $hash) === $hash){
echo "true";
} else {
echo "false";
}
You should be using the submitHandler to write a function to handle the actual checking of the username/password via AJAX using AJAX Form: http://www.malsup.com/jquery/form/#api.
You don't have to use AJAX Form and can write your own method to handle the login checking using the jQuery ajax() method, but AJAX Form has it prewritten for you.
Also, you don't need the onkeyup, onblur, etc. there - all you need is onsubmit set to true. Your code should look like this:
<script>
$('#login').bind('pageinit', function(event) {
$('#loginForm').ajaxForm(); // Set as an AJAX Form - See Documentation Above
$('#loginForm').validate({
onsubmit: true,
rules: {
email: {
required: true,
email: true
},
pass: {
required: true
}
},
messages: {
email: {
required: "You must enter an email address.",
email: "You must enter a valid email address."
},
pass: {
required: "You must enter a password.",
}
},
submitHandler: function(form) {
$("#loginForm").ajaxSubmit();
}
});
});
</script>

JQuery Validation is not working

I have one form in which one input type whose value is "First Name". But this can be changed on onfocus function I want validation for this input field if it is blank or "First name"
I have two jQuery files jquery-1.4.2.min.js & jquery.validate.pack.js.
I have another jQuery file for this form:
jQuery(document).ready(function() {
jQuery("#frmRegister").validate({
errorElement:'div',
rules: {
Fname:{
required:true,
minlength: 2,
maxlength:30
}
},
messages: {
Fname:{
required: "Please enter first name",
minlength: "Required minimum 2 characters allowed",
maxlength: "Required maximum 30 characters allowed"
}
});
jQuery("#msg").fadeOut(5000);
});
In this file required:true is working if value is blank but by default value is "First Name" so it does not work I want both if it is blank or it is "First Name".
<form name="frmRegister" id="frmRegister" method="post">
<ul class="reset ovfl-hidden join">
<li class="fall">
<label for="Fname">Full Name:</label>
<div class="fl">
<input type="text" class="form" id="Fname" name="Fname" value="First Name" onfocus="if(this.value=='First Name')this.value='';" onblur="if(this.value=='')this.value='First Name';" />
</div>
</li>
</ul>
</form>
Please reply as early as possible.
Thank you.
You can use required rule with Callback and check for equality with First Name before returning
You should create custom validation rules for such cases as described here: jquery.validation - how to ignore default values when validating mandatory fields
this is my code it's working properly: try this
$().ready(function() {
$("#form2").validate();
// validate signup form on keyup and submit
$("#form1").validate({
rules: {
userid: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
authority: {
required: true
},
emailid: {
required: true,
email: true
}
},
messages: {
userid: "Please enter your user Id",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
emailid: "Please enter a valid email address",
authority:"Please select Authority"
},
}
});
Did u try the adding custom validation ]
jQuery.validator.addMethod("workPublicserviceDate",
function(value, element) {
var hint = '<?php echo $dateHint; ?>';
var format = '<?php echo $format; ?>';
var pubService = strToDate($('#txtAPS').val(), format)
var dateAssume = strToDate($('#txtAssumeDate').val(), format);
if (pubService && dateAssume && (pubService > dateAssume)) {
return false;
}
return true;
}, ""
);
Pls note i have added example
$("#frmEmpJobDetails").validate({
rules: {
txtAPS: { workPublicserviceDate: function(){ return ['<?php echo $dateHint; ?>','<?php echo $format; ?>']}, required:true },
}
messages: {
txtAPS : { workPublicserviceDate: '<?php echo __("Invalid date."); ?>',
}

Categories