I am using bassistance.de's Validation jQuery plugin to validate a form #signup-form. Instead of submitting the form data directly to the server the usual way, the form data should be submitted AJAX'ly via $.post().
JS Code
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
});
Problem: If a user entered data that does not pass the jquery validation, the click handler on #submit-btn will still allow the form to be submitted! Is there a way to check that there are no validation errors?
Try this:
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
if ($('.signup-form').valid()) {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
The best way to do this is to use the submitHandler option to validate:
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
},
submitHandler: function(form){
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
This will automatically be called once the form is valid. No need to attach anything new to your submit button or the submit event.
Related
I am working with ajax Php, I want to check email availability using ajax(on blur function)
my code is working fine, showing whether email exists or not but my form submitting even " email already exists " message showing
, I just want that form should not submit if I enter existing email, Here is my code, Where I am wrong?
<script type = "text/javascript" >
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function() {
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if (filter.test(email_val)) {
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/Register/email_check", {
email: email_val
}, function(response) {
alert(response);
$('#loading').hide();
//$('#message').html('').html(response).show().delay(4000).fadeOut();
if (response.trim() == '1') {
$('#failuremsg').show().delay(4000).fadeOut();
} else {
$('#successmsg').show().delay(4000).fadeOut();
}
});
return false;
}
});
});
</script>
replace the submit button on the form with
<button id="submit-form">Submit</button>
set a validated=true variable in your main code when all checks have passed
add some jquery
$( "#submit-form" ).click(function() {
if(validated){
$( "#yourForm" ).submit();
}else{
return false;
}
};
Problem
JQuery Validate does not work. In the below plunker, Please click on "Please click here" button and then click on save. It will not validate form.
Sample code in Plunker
I have jQuery validation code which is working fine in case I open the add/update form in new page. I meant by redirecting the user to a new route.
$("form#" + createRoleForm).validate({
rules: {
},
messages: {
},
submitHandler: function(form) {
}
});
In case I open the add/update form on clicking the button in same page when I am inside List page...The above jQuery validate code does not work. I am assuming that I will need something like this...
$(document).ready(function() {
$(document).on("eventtype", "object", function() {
});
});
But, I am not sure how can I bind the validate event in this way....
Since your form is async, your element is not already on the dom when you are creating the validator.
What you should do is add the validate code on your ajax success function:
//...
success: function(result) {
$('#SaveRoleModal').html(result);
createValidator("form#" + createRoleForm)
return false;
},
//...
function createValidator(target) {
$(target).validate({
rules: {
Role: {
required: true
}
},
messages: {
Role: {
required: "Please enter Role"
}
},
submitHandler: function(form) {
console.log('ok :)')
}
});
}
I am using Codeigniter and i am creating a login registration form which check the email of user that it available or not. User can login with that id.
So I am Trying to use Ajax for it.
So I have Put this Ajax in my View.
$(document).ready(function() {
$("#email").keyup(function() {
var email = $(this).val();
if (email.length > 3) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: emailAvailability,
data: { email: email },
success: function(data) {
console.log(data);
$("#result").html(data);
if (data.indexOf('Available')) {
emailAvaliable = 1;
//$('#candidateLogin').removeClass('disabled');
} else {
emailAvaliable = 0;
//$('#candidateLogin').addClass('disabled');
}
}
});
return false;
} else {
$("#result").html('');
}
});
});
I am Using parsley plugin for validation.
$(".formValidationClass").on('click', function (e) {
e.preventDefault;
$(this).parsley();
});
Now the Controller Code.
public function check_email_availability(){
$data = $this->input->post();
// Now I want to check email is unique or not without going to database.
}
The Second Problem is i want to disable the form till email is available & valid.
I have tried this script to disable the form to submit but it's not working and form get submitted. I have done the server side validation to not submit but still i want to prevent it form the client side.
this is the script.
$(".formValidationClass").on('click', function(e) {
e.preventDefault;
$(this).parsley().validate();
console.log('on form click, After validation');
// return false;
});
var emailAvaliable = 0;
$(".formValidationClass").submit(function(event) {
// Validate form fields
if (emailAvaliable == 1) {
console.log('Email Avaliable');
$(this).parsley();
return true;
} else {
console.log('Email not Avaliable');
return false;
}
});
All the suggestion related improving the code is acceptable. Thanks.
if you want to prevent the form submit event then please use: e.PreventDefault(); Check this Using JQuery - preventing form from submitting for more information. I think this is useful for you.
Hey guys with this line of code I enable the jQuery validator to validate certain form fields.
<script>
$(function()
{
$( "#date").datepicker( {autoSize: true, dateFormat: 'yy/mm/dd', showAnim: 'show' } );
});
$(function()
{
$( "#starttime, #stoptime, #starttime2, #stoptime2, #starttime3, #stoptime3, #starttime4, #stoptime4" ).timepicker( {autoSize: false, showAnim: 'show' } );
});
</script>
<script>
$(function() {
$("#productionlogform").validate({
rules: {
date: {
required: true,
},
starttime: {
required: true,
},
stoptime: {
required: true,
}
}
});
});
</script>
As you see, date, starttime and stoptime are required, therefore the form can not be posted before it's set.
Now this is VERY annoying if I have a delete button in my form...
Any idea's how to allow that button to bypass the validation rules?
Also, don't forget to validate on the server side as well. Client-side validation should never, ever, EVER, be relied upon to prevent people entering bad/malicious data.
Sorry Bhavik Shah that I can not accept your answer, but anyway, the validationEventTrigger did the job. Rewrote my code and looks like this:
<script>
$(function() {
$("#deleteproductionlog").click(function () {
$("#productionlogform").validate().cancelSubmit = true;
});
$("#newproductionlog").click(function () {
$("#productionlogform").validate().cancelSubmit = true;
});
$("#productionlogform").validate({
rules: {
date: {
required: true,
},
starttime: {
required: true,
},
stoptime: {
required: true,
}
},
});
});
</script>
The button named "deleteproductionlog" and "newproductionlog" will skip the validation of the form, which is called "productionlogform".
I'm using Yii user side validation in static forms and it's great.
But I don't know how to add validators for ajax loaded elements.
I have simple form widget and I would like to load few more input fields into it via AJAX (that's not problem with small jQuery script). But I don't know how to add Yii javascript validators for loaded elements - I mean auto created JS validators like:
<script type="text/javascript">
/*<![CDATA[*/
jQuery(function($) {
$('#newsletter-form-footer').yiiactiveform({'validateOnSubmit':true,'validateOnChange':false,'afterValidate':Form.handleByAjax,'attributes':[{'id':'NewsletterForm_emailaddress','inputID':'NewsletterForm_emailaddress','errorID':'NewsletterForm_emailaddress_em_','model':'NewsletterForm','name':'emailaddress','enableAjaxValidation':false,'clientValidation':function(value, messages, attribute) {
if($.trim(value)=='') {
messages.push(" VALIDATOR_REQUIRED");
}
if($.trim(value)!='' && !value.match(/^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/)) {
messages.push(" VALIDATOR_EMAIL");
}
}}]});
});
/*]]>*/
</script>
Is there any way how to add or remove that validators?
This is little bit tricky... If you want to do it using yiiactiveform, you have to:
Add a field to validation, or
Remove a field from validation
My suggestion is:
Create your own JavaScript validation functions (you may want to copy yii's validation code here)
$('#newsletter-form-footer').submit(function() {
return MyValidator.validate();
});
When you load a field into the form
//You have to get rulesORoptions
// along with fieldName from your ajax request.
MyValidator.add(fieldName, rulesORoptions);
When you Remove a field out of the form
MyValidator.remove(fieldName);
MyValidator code here...
var MyValidator = {
fields: {},
add: function(fieldName, rulesORoptions) {
this.fields[fieldName] = rulesORoptions;
},
remove: function(fieldName) {
delete this.fields[fieldName];
},
validate: function() {
var success = true;
for(var fieldName in this.fields) {
for(var rule in this.fields[fieldName]) {
if( eval('MyValidator.'+rule+'($("#'+fieldName+'").val())') == false ) {
$("#'+fieldName+'_em_").html("validation failed (some error text, rulesORoptions may contain error text )");
success = false;
}
}
}
return success;
},
/* Validation methods are here,
copy the javascript validation code from Yii
*/
email: function(value) {
if($.trim(value)!='' && !value.match(/^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/)) {
return false;
}
return true;
},
required: function(value) {
if($.trim(value)=='') {
return false;
}
return true;
},
number: function(value) {
if(/*copy yii validation code */) {
return false;
}
return true;
},
.....
.....
};