jQuery Validation plugin rules to specific form - javascript

I'm using the jQuery Validation plugin to validate my forms. Now I want to validate each form on my site. This works:
$('form').validate({
<?php echo $translation["validation_lang"];?>
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
success: function (label, element) {
$(element).tooltipster('hide');
}
});
I'm using Tooltipster to show the errors next to their corresponding field. Again, this works. The PHP-string in there is to optionally load a language pack.
Now I have other forms on my site that require additional rules. For example, the register form should check username availability, check username validity (length, characters, ...), etc.
$('#registerForm').validate({
rules: {
username: {
minlength: 3,
maxlength: 50
},
password1: {
minlength: 5
},
password2: {
minlength: 5,
equalTo: "#password1"
},
email: {
remote:{
url: "getContent.php",
type: "post",
data: {
type: "checkMail"
}
}
},
username: {
remote: {
url: "getContent.php",
type: "post",
data: {
type: "checkUser"
}
}
}
},
messages: {
email: {
remote: "<?php echo $translation["already_registered"][0];?>"
},
username: {
remote: "<?php echo $translation["already_registered"][1];?>"
}
}
});
Having these two snippets of code on the same page does not work. When having the body of the code above (thus the rules and messages) inside the initial $('form').validate({ instead of it's own $('#registerForm').validate({ it does work. I can't seem to find anywhere how to add certain rules to specific form's, whilst maintaining the 'general' rules for all forms.
So in short: How do I add rules/messages/submitHandlers to specific forms with a certain ID, whilst maintaining the general form-rules?

You can use the setDefaults method to define common validation stuff:
http://jqueryvalidation.org/jQuery.validator.setDefaults/
Example:
$.validator.setDefaults({
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
success: function (label, element) {
$(element).tooltipster('hide');
}
});
jsFiddle - Setting error element to "em" for all forms.

Related

First Click shows validation error and doesn't work. Second click it works fine

I have following JS
jQuery(document).ready(function() {
jQuery("#form").validate({
onfocusout: false,
onkeyup: false,
errorPlacement: function (error, element) {
jQuery(element).tooltipster(tooltipster_config);
jQuery(element).tooltipster('content', jQuery(error).text());
jQuery(element).tooltipster('show');
},
success: function (label, element) {
jQuery(element).tooltipster('hide');
},
rules: {
'user': {
required: true,
remote: {
url: URL,
type: "get",
async: "false",
data: {
user: function () {
return jQuery("input[name=user]").val();
}
}
}
},
},
messages: {
'user': {
required: 'Enter user ID',
remote: 'No User exists'
}
}
});
jQuery("button[id=submit]").click(function (e) {
e.preventDefault();
if (jQuery("#form").valid()) {
jQuery("form").submit();
}
});
});
In the above JS i am trying to validate a form field called 'user'. If i enter a wrong user id as per the rules defined it displays 'No User exists'. But when i correct user id to valid user id, on the first click of submit i still get 'No User exists' error, but on clicking submit second time it works fine.
I also tried 'on' function instead of 'click' but the error still persists. Please let me know where i am getting it wrong.
Try something like this:
$("#form").validate({
rules:
{
user:
{
required: true,
// Remote call
remote: {
url: 'process.php', // On the basis of some condition this return either "true" or "false"
type: 'post',
data: {
user: function() {
return $( "#user" ).val();
}
}
}
}
}
messages:
{
user :
{
required: 'Enter user ID',
remote: 'No User exists'
}
}
});

Jquery form validation before Ajax request

I have gone through other threads and used one for reference but still I am not able to find the solution.
My question is:
I am calling a function on button click now that function has validation after validation I am trying to post data with ajax request in submit handler, problem is my fields are getting verified but Ajax request is not invoked.
<input type="button" value="Register" id="registerP" onclick="registerPatient()" class="form-control input-sm btn-success ">
function registerPatient(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: "patientName=" + patientName,
success: function(response){},
error: function(e){}
});
}
});
}
However if I am not using validation and calling Ajax directly i am able to post the data. Please suggest where I am going Wrong.
You can try like this which call jquery form validation and check if validated:
$(document).ready(function(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
}
});
});
function registerPatient(){
var IsValid=$("#patientRegistration").valid();
if(IsValid){
var patientName=""; //value for patient name
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: {"patientName": patientName},
success: function(response){},
error: function(e){}
});
}
}
Change your data syntax of ajax to this.
data: {patientName:patientName},
Make sure you have a parameter on catching method of the same name "patientName" to invoke its post from page on post.
This should work.
Also check if you get a patientName paramater value in your post. To do so first check by "alert" and pass the patientName parameter. You will know what you are getting and why post is not happening.

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()
}
})

Validate and submit form with no page refresh

I'm using jQuery validation and processing the form via ajax so I can avoid a page refresh. The problem I am running into is that I can't figure out where to place the ajax code in the validation function so that the form won't send data until it's been validated.
For example:
$('#ticket_purchasing').validate({ // initialize the plugin
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
phone: {
required: true,
digits: true,
},
email: {
required: true,
email: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = "All fields in red must be filled*";
$("div.error-message span").html(message);
$("div.error-message").show();
} else {
$("div.error-message").hide();
}
},
submitHandler: function (form) { // for demo
// Do stuff here
}
});
$('form#ticket_purchasing').on('submit',function(e) {
//Send the serialized data to mailer.php.
$.ajax({
url:'ticket-purchase.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
// $('#sponsorship_request').slideUp();
// $('#ticket_purchasing').hide();
// $('.seats-form').fadeIn(1000);
},
error:function(data){
$("ticket_purchasing .error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
//$.post("mailer.php");
//Take our response, and replace whatever is in the "form2"
//div with it.
// $('#form2').show();
});
As you can see above I have both functions separated from each other, and because of this the form is submitting the data (which emails the information) even though it's not been validated yet. I tried using form.submit(); as show in the validator documentation, and putting the ajax code in there, but it was a no go with errors I couldn't solve.
Advice? I'm probably going at this all wrong haha.
Edit: Just added html for the form: https://gist.github.com/adrianrodriguez/26b6beee8bf5ba85a8ce
To be clear, the form works fine without the validation portion, meaning I can submit and collect the data without a page refresh without the use of the validation plugin.
Remove your $.ajax call as the actual form submission should happen after validation in the validate.submitHandler.
$('form#ticket_purchasing').validate({
//validation rules here
//invalid handler goes here
submitHandler: function(form) {
$.post('ticket-purchase.php', $('#ticket_purchasing').serialize(), successCallback());
}
});
BTW, changed your $.ajax to a $.post
Thanks for everyone's help. I eventually realized that I was going at it all wrong and found this answer:
submitHandler: function (form) { // for demo
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(data) {
console.log(data);
// Do stuff here
//$('#ticket_purchasing').hide();
//$('.seats-form').fadeIn(1000);
}
});
return false; // kill page refresh
}
Instead of going the traditional way of the ajax submit I just had to use the "form" parameter already provided from jquery.validation.js and then grab data from its attributes.
Thanks for everyones help!
$( "#target" ).submit(function( event ) {
});
between this.

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