I'm trying to use parsley's js custom validator to check for a unique email address on my form. However it's not stopping the form from submitting when I not matter what I return.
The ajax request checkEmailExists returns true or false depending on if the email exists
window.Parsley
.addValidator('uniqueUsername', {
requirementType: 'string',
validateString: function(value, requirement) {
$.ajax({
url: "checkEmailExists",
data: {username: value},
dataType: 'json',
method: 'POST',
data: { email: $( "#email" ).val() },
async: false,
success: function(data) {
return data;
}
});
},
messages: {
en: 'This email address already exists!'
}
});
<input type="text" id="email" name="email" placeholder="Email" data-parsley-uniqueUsername data-parsley-required="true" data-parsley-type="email"/>
The promise you are returning must fail or succeed, not succeed with true or false.
Easiest is probably to use the remote validator.
Not relevant, but for idempotent requests like these, you're supposed to use GET, not POST.
As Marc said your promise must fail for succeed and also your validator name can't have capital letters or special characters so try something like this:
// uniqueUsername validator
window.Parsley.addValidator('uniqueusername', {
validateString: function (value, requirement) {
xhr = $.ajax({
url: "users_list_ajax.php",
dataType: 'json',
method: 'GET',
data: {
action: 'checkUserExists',
username: value
}
});
return xhr.then(function (data) {
console.log((data.isUnique == 0));
if (data.isUnique == 0) {
return true;
} else {
return $.Deferred().reject();
}
});
},
messages: {
en: 'Username already exists!',
ar: 'إسم المستخدم موجود مسبقا'
},
priority: 32
});
Related
I need to wrote a code on an older version of the .net Framework, namely 4.5.2.
I ran into a problem, the ajax code sends an empty request to the controller.
Here is the form and I need to check user Full Name on unique:
<div class="register-card">
<h1>Register the new user</h1>
#using (Html.BeginForm("CreateUserAsync", "Home", FormMethod.Post))
{
<div>
#Html.Label("FullName", "Enter your full name")
<input type="text" id="FullName" name="FullName" pattern="^(\w\w+)\s(\w+)\s(\w+)$" onblur="CheckAvailability()" required />
<span id="message" onclick="ClearMessage()"></span>
</div>
<p><input type="submit" value="Send" id="submit" /></p>
}
</div>
Here is my js function to checking Full Name:
function CheckAvailability() {
var data = $("#FullName").val();
var param = data;
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "String",
data: JSON.stringify(param),
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
};
function ClearMessage() {
$("#message").html("");
};
Js function pass the FullName to next controller:
[HttpPost]
public async Task<JsonResult> CheckFullNameAsync([FromBody]string fullName)
{
var isValid = await _service.IsUserExistAsync(fullName);
return Json(isValid);
}
But the controller receives null.
I think the problem is in the Js function, but I can figure out what I'm doing wrong.
Dont need to create two variable
var data = $("#FullName").val();
var param = data;
Just create
var param = $("#FullName").val();
try this
Check this link. it explains your problem well
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: 'json',
data:{"":param},
//data: { fullName: param },
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
or this one also
$.post('/Home/CheckFullNameAsync', { fullname: param},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
What is dataType: "String"? That's not a listed option. And more specifically, all you're sending is a value but with no key. So the server isn't able to deserialize the data and determine where the fullName value comes from.
Change the type to 'json' and send the object with the named key for the value:
dataType: "json",
data: { fullName: param },
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){
}
});
I am using jQuery plugin for my validation on one ajax calls.
Currently I have this:
$("#invoiceForm").validate({
rules: {
plateNumber: {
required: true,
},
plateIssueState: {
required: true,
}
},
submitHandler: function(form) {
var invoice= 1 + Math.floor(Math.random() * 999999999);
$.ajax({
type: "POST",
url: "invoice",
data: $(form).serialize(),
success: function() {
},
error: function() {
}
});
return false;
}
});
The submitHandler was able to serialize all the data from the HTML form, but this is not enough for me. I need to also send the variable invoice to the back-end however invoice variable is not in the form. I have tried to do something like this but failed, it will not in the correct JSON data format:
data: JSON.stringify({invoiceData:invoice, formData:form}),
How can I change this?
Since your invoice value ist just a single variable, you could append it to the data string:
$("#invoiceForm").validate({
rules: {
plateNumber: {
required: true,
},
plateIssueState: {
required: true,
}
},
submitHandler: function(form) {
var invoice= 1 + Math.floor(Math.random() * 999999999);
var formData = $(form).serializeArray().map(function(obj) {
var o = {};
o[obj.name] = obj.value;
return o;
});
var data = {
formData: formData,
invoiceData: invoice
};
$.ajax({
type: "POST",
url: "invoice",
data: JSON.stringify(data), // Send the concatenated values
success: function() {
},
error: function() {
}
});
return false;
}
});
If you want to send the invoice variable along with your form, you simply need to include an invoice input field. This can be a hidden field that gets populated just before your serialize your form data.
Assuming your have something like:
HTML:
<input type="hidden" name="invoice" id="InvoiceData" />
You would then just add that data directly:
javascript:
var invoice = 1 + Math.floor(Math.random() * 999999999);
$('#InvoiceData').val(invoice);
Try this:
...
data: $(form).serialize() + '&invoiceData=' + JSON.stringify(invoice),
dataType:'json',
...
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()
}
})
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