Check username availability with jquery validation plugin (servlet and jsp) [duplicate] - javascript

This question already has answers here:
jQuery Validate remote method usage to check if username already exists
(2 answers)
JQuery Remote Validation not displaying Error [duplicate]
(2 answers)
Closed 5 years ago.
I an using jquery validator plugin to validate my registration form. However, when I tried to check if an username is in the database, it does not work. Can anyone help take a look at my codes and let me know what I did wrong? It always shows user already exist even when the username is not in database.
I have tried the methods from
jQuery Validate remote method usage to check if username already
exists and JQuery Remote Validation not displaying Error
but it still doesn't work.
My registration jquery function:
$().ready(function() {
$.validator.addMethod('uniqueUsername', function(value) {
$.ajax({
url: 'http://localhost:8080/TBS-war/RegisterServlet.java',
type: 'POST',
async: false,
contentType: 'application/json',
dataType: 'json'
});
});
//Validate signup form on keyup and submit
$("#registrationForm").validate({
// Set rules
rules: {
username: {
required: true,
uniqueUsername: true
/*remote: {
url: "http://localhost:8080/TBS-war/RegisterServlet.java",
type: "post",
contentType: "application/json",
data: {
'username': $('#username').val()
}
}*/
},
password: {
required: true
},
confirmPassword: {
required: true,
equalTo: "#password"
},
contact: {
required: true
},
email: {
required: true,
email: true
},
address: {
required: true
}},
// Set messages
messages: {
username: {
required: "* This field is required",
uniqueUsername: "* User already exist"
//remote: "* User already exist"
},
password: {
required: "* This field is required"
},
confirmPassword: {
required: "* This field is required",
equalTo: "* Please enter the same password as above"
},
contact: {
required: "* This field is required"
},
email: {
required: "* This field is required",
email: "* Please enter a valid email"
},
address: {
required: "* This field is required"
}},
My servlet file:
#EJB
private TBSManagerBeanRemote tBSManagerBean;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
String username = request.getParameter("username");
if (tBSManagerBean.userExist(username)) {
out.print("{\"valid\" : false }");
json.put("valid", false);
System.out.println("false");
}
else {
out.print("{\"valid\" : true }");
json.put("valid", true);
System.out.println("true");
}
}

Related

How to Add ajax form processing for html mail form

I currently finished creating ( modify a themeforest template ) a website and all i need to do now is to set up contact form to receive mail from my customers
/* *****************************************************************
* FORM VALIDATION
* ************************************************************** */
$("#contactForm").validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true
}
},
messages: {
fullname: {
required: "Please enter your name"
},
email: "Please enter a valid email address",
message: "Please enter your message"
},
submitHandler: function () {
// Add your ajax form processing here.
}
});
This is the code form config.js file. How do i set up with my mail ( contact#website.com )
$.ajax({type:'POST', url: 'contact.php', data:$('#contactForm').serialize(), success: function(response) { $('#contactForm').find('.form-control').html(response);}});
this is the final syntax that works perfectly
try this
var data = new FormData($("#contactForm")[0]);
$.ajax({
url : 'your url ',
type : 'post',
data : data,
mimeType : 'multipart/form-data'
contentType: false,
processData: false,
success: function(data){
}
});

How can I validate if email exists

I am using the jQuery validation plugin and it works correctly , but I have a problem checking email. I receive true or false dependant on if email exists or not. However I don't know how to change the state of validation in the form, because I can't pass the validation.
email: {
required: true,
email: true,
remote: {
url: "checkEmail",
type: "get",
success: function(data){
if (data.msg == true) {
///Email avaliable////
console.log("OK");
} else {
/////Email taken///
console.log("NO");
}
}
},
},
Could anyone help me?
Considering that the ajax call returns true or false based on data , you can try the following code snippet of email rule and messages rule .
email: {
required: true,
email: true,
remote: {
url: "checkEmail",
type: "post",
data: {
email: function() {
return $('#formID :input[name="email"]').val();
}
}
}
},
messages: {
email: {
required: "Please enter your email address.",
email: "Please enter a valid email address.",
remote: jQuery.validator.format("{0} is already taken.")
}
}

JQuery validator plugin passing data

I have a form with JQuery validator being applied to it. I wont post it all, but the code looks like the following
var validator = $("#my_form").validate({
errorPlacement: function(error, element) {
$( element )
.closest( "form" )
.find( "#error" )
.append( error );
},
rules: {
emailAddress: {
require_from_group: [1, '.datagroup'],
email: true,
maxlength: 40
},
mobileNumber: {
require_from_group: [1, '.datagroup'],
number:true,
minlength: 8
}
},
messages: {
emailAddress: {
maxlength: jQuery.validator.format("shorter")
},
mobileNumber: {
number: jQuery.validator.format("Please enter a number"),
minlength: jQuery.validator.format("Please enter a valid number")
}
},
groups: {
datagroup: "emailAddress mobileNumber"
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "php/main.php",
data: $(form).serialize()
})
.done(function (response) {
$('#results').html(response)
});
return false;
}
});
The problem is that the submit handler is passed the whole form, and then this data is serialized and sent to main.php. However,I no longer want the format it is submitting the mobileNumber in. The reason for this is that I am now using a plugin which will format this number for me, and to get the value of this, I need to do
var mobileNumber = $("#mobileNumber").intlTelInput("getNumber");
I can also grab the email using val() so this can be assigned to a variable as well. So how can I pass main.php the variables mobileNumber and emailAddress?
Thanks
You could do so, by manually constructing the data object like below.
$.ajax({
type: "POST",
url: "php/main.php",
data: {
'emailAddress': $("#mobileNumber").intlTelInput("getNumber"),
'mobileNumber': $("selector").val()
}
})

jquery validation and ajax form submit

I have problem with jquery validation and ajax form submit.
Here's validation code:
$(function() {
$("#contact-form").validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 32
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 20
}
},
messages: {
name: {
required: "Please, enter a name",
minlength: $.format("Keep typing, at least {0} characters required"),
maxlength: $.format("Whoa! Maximum {0} characters allowed")
},
email: {
required: "Please, enter an email",
email: $.format("Please, enter valid email")
},
message: {
required: "Please, enter a message",
minlength: $.format("Keep typing, at least {0} characters required")
}
},
submitHandler:function(form) {
form.submit();
}
});
});
Here's ajax code for submitting the form:
$(document).ready(function(){
$('#contact-form').on('submit',function(e) {
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$.ajax({
url:'',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
e.preventDefault();
});
});
What I try to do is form validation and then submit the form. After submit the form should appear again with initial values.
The problem is that when I remove ajax then validation works fine, but I need ajax code to re-display the form.
How I could make this two pieces of code work together?
Place your ajax call within the submitHandler function:
submitHandler:function(form) {
//form.submit();
$.ajax({
url:'', //you will need a url surely, perhaps $(form).attr('action');
data:$(form).serialize(),
type:'POST',
success:function(data){
console.log(data);
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
}

How do I define the value of an input for a remote check of existing values (username)?

This is using jQuery 1.6.1 and Validate 1.8.1.
I have been banging my head against a wall because of this problem, and now I'm trying the other approach to try and solve this problem. I need to query the database for existing usernames so that someone signing up doesn't register the same one again.
HTML:
<form class="cmxform" action="register.php" method="post" name="signup" id="signup">
<ul>
<li>
<label for="username">Username: <em>*</em></label>
<input type="text" id="username" name="Username" size="20" class="required" placeholder="Username" />
</li>
</ul>
</form>
This time, I'm trying to use the remote function for the validate script:
$("#signup").validate( {
var username = $("#username").val();
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
},
},
submitHandler: function(form) {
form.submit();
}
});
The code in question that doesn't work is var username = = $("#uname").val();. Firebug gives the error missing : after property id.
I'm including the mentioned variable above inside validate() because I only want the value of the input after I've typed something into it, not upon loading of the page.
The other problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
What am I doing wrong?
As you can read How can I force jQuery Validate to check for duplicate username in database?
The solution is to use the remote property:
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
var username = $("#uname").val();
instead of
var username = = $("#uname").val();
You can't have = =, it's a syntax error.
Also, make sure you properly 'escape' $("#username").val().
If someone enters: myname&action=dosomethingelse I'd give it a fair change it will dosomethingelse.
New answer:
$("#signup").validate( {
var username = $("#username").val(); // -- this is wrong
rules: {
Username: {
required: true,
...
});
You can fix this the easy way by just not declaring the variable at all since you're only using it is one place, but that's no fun :D
The solution is a closure:
$("#signup").validate( (function () {
var username = $("#username").val();
return {
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
}
},
submitHandler: function(form) {
form.submit();
}
};
}()));
(I haven't tested it, there may be a typo or syntax error).
If you have no idea what this does or why, don't worry about it :D

Categories