Jquery validation

jd_18286
jd_18286 used Ask the Experts™
on
Hi, im looking for a script that can validate form fields in ajax using query but at the same time to check username Availability in my SQL db i've been lokking on google and i only find scripts to validate fields with query but none checks username Availability in SQL i was wondering if i can get some help on that. im posting a interesting script i found for validating fields but dosent checks Availability of username in DB
http://yensdesign.com/tutorials/validateform/

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
I like the jQuery validation plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ - very easy to use, and supports both 'local' validation as well as remote validation, i.e. checking a username against a database.  Basically you need a server-side script in whatever language you're using  - .Net, PHP, etc. that connects to the database, checks the username, and then responds either 'true' the username does not exists or 'false' the username does exist.

So let's say you have a form with the id 'signup', and it has a field with the name 'username', and you've created a PHP script check_username.php.

See http://docs.jquery.com/Plugins/Validation/Methods/remote#options for more details on how the remote function works.

<script type="text/javascript">
$(document).ready(function() {
  $('#signup').validate(
    rules: {
      username: {
        required: true,
        remote: 'check_username.php'
      }
    },
    messages: {
      username: {
        required: 'Please enter a username',
        remote: 'This username is already taken'
      }
    }
  );
});
</script>

Open in new window

Author

Commented:
i was just exploring that site and i found this sigup form http://jquery.bassistance.de/validate/demo/milk/ it's exactly what im looking for my question is it's calling the users.php file i would likt to know whats inside of that users.php file.
remote: "users.php" 

Open in new window

Commented:
So if the field is named username, it would basically look like this:


<?php
$username = $_GET['username'];
 
//Connect to your database here
 
$sql = "SELECT * FROM users WHERE username = '$username'";
$num_rows = mysql_num_rows(mysql_query($sql));
if ($num_rows != 0)
  echo 'false';
else
  echo 'true';

Open in new window

Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Author

Commented:
im having a little error in the file users.php i have an array with 4 names but in the error i always get "peter is already in uses" even when i put other name like George in the Username Field what could be the problem?
-------------------------USER.PHP--------------------------------------
<?php
$request = trim(strtolower($_REQUEST['username']));
//sleep(2);
usleep(150000);
$users = array('asdf', 'Peter', 'Peter2', 'George');
$valid = 'true';
foreach($users as $user) {
	if( strtolower($user) == $request )
		$valid = 'false';
}
echo $valid;
?>
----------------------------END OF USERS.PHP---------------------------
 
----------------------------SCRIPT IN INDEX.HTML-----------------------
<script id="demo" type="text/javascript">
$(document).ready(function() {
	// validate signup form on keyup and submit
	var validator = $("#signupform").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			username: {
				required: true,
				minlength: 2,
				remote: "users.php"
			},
			password: {
				required: true,
				minlength: 5
			},
			password_confirm: {
				required: true,
				minlength: 5,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true,
				remote: "emails.php"
			},
			dateformat: "required",
			terms: "required"
		},
		messages: {
			firstname: "Enter your firstname",
			lastname: "Enter your lastname",
			username: {
				required: "Enter a username",
				minlength: jQuery.format("Enter at least {0} characters"),
				remote: jQuery.format("{0} is already in usesss")
			},
			password: {
				required: "Provide a password",
				rangelength: jQuery.format("Enter at least {0} characters")
			},
			password_confirm: {
				required: "Repeat your password",
				minlength: jQuery.format("Enter at least {0} characters"),
				equalTo: "Enter the same password as above"
			},
			email: {
				required: "Please enter a valid email address",
				minlength: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			},
			dateformat: "Choose your preferred dateformat",
			terms: " "
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.parent().next() );
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function() {
			alert("submitted!");
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		}
	});
	
	// propose username by combining first- and lastname
	$("#username").focus(function() {
		var firstname = $("#firstname").val();
		var lastname = $("#lastname").val();
		if(firstname && lastname && !this.value) {
			this.value = firstname + "." + lastname;
		}
	});
 
});
</script>
--------------------------END OF SCRIPT--------------------------------

Open in new window

Commented:
It's actually kinda a bug with the validation script; the same thing happens on that demo page.  To get around it tho you should be able to explicitly specify that you want to use the value from the username field as the value in that template.  Try using this instead:

jQuery.format("{0} is already in usesss", $('#username').val())

Open in new window

Author

Commented:
tx that worked for me any way of making the field red if its incorrect and green if its correct? also i was looking at the code and i only found a digit rule but i would like to validate alpha characters is any way to make this?

Commented:
You want to change the colors of the actual text fields?  When the script marks a field as invalid, it automatically applies the class 'error' to it.  So all you need to do to make it red is to create a class in your CSS file or in your page that sets the background or text color appropriately:

input.error {color:red;}

There's a success function for validation, that takes the error label in as the parameter.  So we find the input field that label refers to, and add the success class to it

input.success {color:green;}

You've already got the success function in your script, so just change it to look like this:
success: function(label) {
  // set   as text for IE
  label.html(" ");
  var id = label.attr('for');
  $('#' + id).addClass('success');
}

What exactly do you mean by 'validate alpha characters'?

Author

Commented:
well im having 2 problems with that code u sent me first when i make and error the text of the field goes red and when there are no errors it goes green but here is the problem if i go wrong again it stays on green when it should change to red again also i would like the field to change color not the text and also with that code u sent me it replaces the .addClass("checked"); and im not getting the correct image on success and about the  'validate alpha characters' i want to put a rule that lets say in the field First Name they could only write alpha just words no digits and no symbols any clue of how to get this done]?
Commented:
So to keep the checked icon:

success: function(label) {
    // set   as text for IE
    label.html(" ").addClass('checked');
    var id = label.attr('for');
    $('#' + id).addClass('success');
}

Then tweak the errorPlacement function to remove the success class from the element on error:

errorPlacement: function(error, element) {
  element.removeClass('success');
  if ( element.is(":radio") )
    error.appendTo( element.parent().next().next() );
  else if ( element.is(":checkbox") )
    error.appendTo ( element.next() );
  else
    error.appendTo( element.parent().next() );
}

To change the background colors of the fields instead of text colors:

input.error {background-color:red;}
input.success {background-color:green;}

And for the alpha characters, you create a new validator function with a regex that only accepts alpha characters:

$.validator.methods.alphaOnly = function(value,element,param)
{
  if (param) {
    var reg = /^([a-zA-Z+)$/;
    if(! element.val().match(reg))
    {
      return false;
    }
  }
 
  return true;
}

Then use it:

username: {
  required: true,
  minlength: 2,
  remote: "users.php",
  alphaOnly: true
}

Author

Commented:
im still having the problem that the field goes green but if i make an error again the background color is still on green it should go to red

Commented:
Can you post up the HTML and JS code you have?

Author

Commented:
ok here u go
http://webtecdesign.net/milk/

Open in new window

Author

Commented:
ok i think i fixed it i just added in the milk.css this:

input.error {background-color:red;}
input.valid {background-color:green;}

and that did the work about the alpha i was looking in th jquery.validate.js and i found this for digits:

// http://docs.jquery.com/Plugins/Validation/Methods/digits
            digits: function(value, element) {
                  return this.optional(element) || /^\d+$/.test(value);
            },
            
so i made this but im gettin an error in JS

// http://docs.jquery.com/Plugins/Validation/Methods/digits
            alpha: function(value, element) {
                  return this.optional(element) || /^([a-zA-Z+)$/.test(value);
            },
            

Commented:
what's the JS error that you're getting?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial