jQuery validation is working fine but it's not working for array. Please check the working code in here.
http://jsfiddle.net/rq5ra/1050/
If I added array in input then it's not working.
html code
<form id="createprofile">
<input type="file" name="profilepic[]">
<input type="file" name="profilepic[]">
<input type="submit" />
</form>
jQuery code
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');
jQuery(function ($) {
"use strict";
$('#createprofile').validate({
errorElement: "label"
, errorClass: "has-error"
, submitHandler: function (form) {
form.submit(); //return false;
}
, highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('has-error');
}
, rules: {
profilepic[]: {
extension: "jpg,jpeg"
, filesize: 300000, //500kb
}
},
messages: {
profilepic[]: {
extension: "Please upload only jpg, jpeg format"
,filesize: "Please upload maximum 500Kb"
}
}
});
});
Please help me to fix it.
Please add "profilepicp[]"
working code http://jsfiddle.net/rq5ra/1052/
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)}, 'File size must be less than {0}');
jQuery(function ($) {
"use strict";
$('#createprofile').validate({
errorElement: "label"
, errorClass: "has-error"
, submitHandler: function (form) {
form.submit(); //return false;
}
, highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('has-error');
}
, rules: {
"profilepic[]": {
extension: "jpg,jpeg"
, filesize: 300000, //500kb
}
, profileurl: {
remote: {
url: "http://localhost:8888/codeigniternew/edit/username_exists"
, type: "post"
}
}
, email: {
required: true
, remote: {
url: "http://localhost:8888/codeigniternew/edit/email_exists"
, type: "post"
}
}
},
messages: {
"profilepic[]": {
extension: "Please upload only jpg, jpeg format"
,filesize: "Please upload maximum 500Kb"
}
}
});
});
html code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form id="FORM_SEND_IMAGE">
<input type="file" id="file" />
<input type="submit" value="submit" />
</form>
jquery code
function getExtension(filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isImage(filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'png':
case 'gif':
//etc
return true;
}
return false;
}
$(document).on('submit', '#FORM_SEND_IMAGE', function(e) {
e.preventDefault();
e.stopPropagation();
function failValidation(msg) {
alert(msg); // just an alert for now but you can spice this up later
return false;
}
var file = $('#file');
if (!isImage(file.val())) {
return failValidation('Please select a valid image');
}
var form_data = new FormData($(this)[0]);
$.ajax({
url: base_url + 'gallery/add',
type: 'POST',
data: form_data,
dataType: 'json',
beforeSend: function() {
console.log('before');
},
error: function(error) {
console.log(error);
},
success: function(data) {
console.log(data);
},
complete: function() {
console.log('complete');
},
processData: false,
contentType: false
});
});
demo jsfiddle
Related
I have a form that uses jQuery.validate.js plugin to validate and submit a form. The form contains a file upload.
I want to submit and upload the image with the validate.js but When I submit the form with the selected image, nothing happens. I've searched for solution, but the ones I got did not solve the problem.
// **EDIT**
// Add method to check imagesize
$.validator.addMethod("imageSize",function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param);
}, "This fileld is required.");
// END: **EDIT**
var addNewsForm, format;
addNewsForm = $("#newsPanel");
format = ['png','jpe?g','gif'];
addNewsForm.on("submit", function(e) {
e.preventDefault();
//validate form
$(this).validate({
errorClass : "error",
rules : {
news_image : {
required : true,
imageSize: 5242880,
accept : format
}
},
messages : {
news_image : {
required : "Please select an image for the news.",
imageSize : "Image size should not be greater than 5MB.",
accept : "Unsupported image format"
},
submitHandler : function(form) {
sendData = {
news_image : $("#newsImage")
}; // end of sendData
$(form).ajaxSubmit({
type : "POST",
data : sendData,
url : "action_news.php",
success : function(getData) {
$("#pageMsg").html(getData);
}
}); // end of ajaxSubmit
}, // end of submitHandler
}); // end of document ready
<form method="get" id="newsPanel" enctype="multipart/form-data">
<div id="pageMsg"></div>
<input type="file" id="newsImage" name="news_image" size="40" id="newsImage">
</form>
Any better way of achieving this?
You're missing a closing } for your messages object, right now the submitHandler is inside the messages object.
You're also missing a }) to close this function addNewsForm.on("submit", function (e) {.
Try using the code below and see if it works.
addNewsForm.on("submit", function (e) {
e.preventDefault();
//validate form
$(this).validate({
errorClass: "error",
rules: {
news_image: {
required: true,
imageSize: 5242880,
accept: format
}
},
messages: {
news_image: {
required: "Please select an image for the news.",
imageSize: "Image size should not be greater than 5MB.",
accept: "Unsupported image format"
},
},
submitHandler: function (form) {
sendData = {
news_image: $("#newsImage")
}; // end of sendData
$(form).ajaxSubmit({
type: "POST",
data: sendData,
url: "action_news.php",
success: function (getData) {
$("#pageMsg").html(getData);
}
}); // end of ajaxSubmit
}, // end of submitHandler
}); // end of document ready
})
I am getting the error "User is unable to be created" despite the user being successfully created. I have commented the part where the eeror was being shown. The details were all being able to be stored into the database. When I change it to alert(arr[0].result), the output was 0. I tried to use inspect to check for any error but there was none.
(function () {
var admin_userid;
var admin_password;
var admin_passwordagain;
var admin_firstname;
var admin_lastname;
var admin_position;
$(document).ready(function () {
$("#NewAdminForm").validate({
rules: {
txtNewLogin: "required",
txtNewPassword: "required",
txtNewPasswordAgain: {
equalTo: "#txtNewPassword"
},
txtFirstName: "required",
txtLastName: "required",
txtNewPosition: "required"
},
messages: {
txtNewLogin: "new user name is required",
txtNewPassword: "new password is required",
txtNewPasswordAgain: "new password again is required and must be the same as new password",
txtFirstName: "First Name is required",
txtLastName: "Last Name is required",
txtNewPosition: "Position is required"
},
focusInvalid: false,
submitHandler: function () {
return false;
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().parent().after());
},
});
$("#btnCreateAccount").bind("click", function () {
savenewuser();
});
});
function savenewuser() {
if ($("#NewAdminForm").valid()) {
admin_userid = $("#txtNewLogin").val();
admin_password = $("#txtNewPassword").val();
admin_passwordagain = $("#txtNewPasswordAgain").val();
admin_firstname = $("#txtFirstName").val();
admin_lastname = $("#txtLastName").val();
admin_position = $("#txtNewPosition").val();
if ($("#NewAdminForm").valid()) {
var url = serverURL() + "/newadmin.php";
var JSONObject = {
"admin_userid": admin_userid,
"admin_password": admin_password,
"admin_firstname": admin_firstname,
"admin_lastname": admin_lastname,
"admin_position": admin_position
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("error");
}
});
}
}
}
function _getAdminResult(arr) {
if (arr[0].result == 1) {
localStorage.setItem("admin_userid", admin_userid);
localStorage.setItem("admin_password", admin_password);
alert("new user created");
window.location = "homepage_admin.php";
}
else {
alert("User is unable to be created"); //error displayed
}
}
})();
form submission using Jquery and Ajax not working in server but it works perfectly in localhost. Whats the reason for this. I using Codeigniter framework.
View
//order.php
<form action="" method="post" id="form_order">
<p><input type="text" name="due_date" /></p>
<p><input type="text" name="name" /></p>
<p><button type="submit">SAVE</button></p>
</form>
<script>
$(document).ready(function(){
(function($) {
"use strict";
$(function() {
$('#form_order').validate({
rules: {
due_date: {
required: true
},
name: {
required: true
}
},
messages: {
due_date: {
required: "date required"
},
name: {
required: "name required"
}
},
$('#loading').show();
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"<?php echo base_url("ordercode"); ?>",
success: function(data) {
$('#loading').hide();
$('#success').show();
$('#success').html(data);
},
error: function() {
$('#loading').hide();
$('#success').show();
$('#success').html('Something went wrong. Tryagain later!');
}
});
}
});
});
})(jQuery)
});
</script>
controller
//Ordercode.php
if($this->input->post('new_order')) {
$due_date = $this->input->post('due_date');
$name = $this->input->post('name');
$add = $this->orders->addOrder($due_date, $name);
if($add === TRUE) {
echo 'Order Added.';
}
else if($add === FALSE) {
echo 'Something went wrong. Tryagain later!';
}
else {
echo 'Something went wrong. Tryagain later!';
}
}
Model
//Orders.php
public function addOrder($due_date_first, $name) {
$data = array(
'order_due_date' => $due_date_first,
'order_name' => $name
);
$add = $this->db->insert('tbl_order', $data);
if($add == 1) {
return TRUE;
}
else {
return FALSE;
}
}
The above code works perfectly in localhost but not in server. Server always returns error.
Output
Server : Something went wrong. Tryagain later!
Localhost : Order Added.
Is there any problem in my coding. Why it's not working in server. Is there any solution. Thankyou.
$(document).ready(function(){
(function($) {
"use strict";
$(function() {
$('#form_order').validate({
rules: {
due_date: {
required: true
},
name: {
required: true
}
},
messages: {
due_date: {
required: "date required"
},
name: {
required: "name required"
}
},
submitHandler: function(form,e) {
e.preventDefault();
var formData = new FormData(form);
$('#loading').show();
$.ajax({
type:"POST",
data: formData,
url:"<?php echo base_url("ordercode"); ?>",
success: function(data) {
$('#loading').hide();
$('#success').show();
$('#success').html(data);
},
error: function() {
$('#loading').hide();
$('#success').show();
$('#success').html('Something went wrong. Tryagain later!');
}
});
}
});
})(jQuery);
});
});
And remove action="" attribute in form tag
edit-txt,updatePassword are two buttons in a single form superAdminDetailsForm . i want to valide this form in both button click. I wrote form validation on each button click .but it doesn't work. edit-txt button is type of text and update password is type of button
$().ready(function() {$('#edit-txt').on('click', function() {
$("#superAdminDetailsForm").validate({
rules: {
superadminEmail:{
required:true,
email:true
},
},
messages: {
superadminEmail:"Please enter your Email id"
},
submitHandler: function(){
var formData =$("#superAdminDetailsForm").serialize();
$.ajax({
url:'/accounts',
type:'post',
datatype: 'json',
data: formData,
success : function(response){
if(response == "true"){
window.location='/accounts';
} else {
alert("false")
}
},
error: function (request,status, error) {
}
});
return false;
}
});
});
$('#updatePassword').on('click', function() {$("#superAdminDetailsForm").validate({
rules: {
oldPassword:"required",
newPassword:"required",
confirmpassword:{
require :"true",
equalTo : "#oldPassword"
}
},
messages: {
oldPassword:"Please enter Old Password ",
newPassword: "Please enter New Password",
confirmpassword:"Retype password is incorrect"
},
submitHandler: function(){//to pass all data of a form serial
var formData =$("#superAdminDetailsForm").serialize();
$.ajax({
url:'/changePassword',
type:'post',
datatype: 'json',
data: formData,
success : function(response){
if(response == "true"){
window.location = '/accounts';
} else {
alert("password incorrect");
}
},
error: function (request,status, error) {
}
});
return false;
}
});
});
});
HTML5 validation isn't working in Safari so I'm using Happy.js.
My form is still submitting via ajax in Safari though with the code below (here is JSFiddle).
How can I validate #email-input before sending the form with ajax?
The code below is checking if ($(this).hasClass('unhappy')) then don't submit form, if it doesn't have class unhappy then submit form. But I guess the problem is that it doesn't have class unhappy from the beginning.
used from this reference: isHappy.js allowing ajax call when not valid
$(document).ready(function() {
function ajaxEmailForm() {
$(".sendingEmailLink, .sentEmailLink").hide();
$('#email-form').submit(function(event) {
event.preventDefault();
var formserialize = $(this).serialize();
var submitButton = $('#submitEmailForm');
$.ajax({
type: 'POST',
url: 'https://formkeep.com/f/MYID',
accept: {
javascript: 'application/javascript'
},
data: formserialize,
beforeSend: function() {
$(".sendEmailLink").hide();
$('.sendingEmailLink').show();
},
complete: function() {
$(".sendingEmailLink").hide();
},
success: function(d) {
$('.sentEmailLink').show();
},
error: function() {
$('.notification-e--phone').slideDown("medium", function() {});
},
}).done(function(data) {
submitButton.prop('disabled', 'disabled');
});
});
};
$('#email-form').isHappy({
fields: {
'#email-input': {
required: true,
test: happy.email,
message: 'Please enter your full email address.',
errorTarget: '.email-input-error'
}
}
});
var is_unhappy = false;
$('#email-form div :input').each(function(i) {
if ($(this).hasClass('unhappy')) {
is_unhappy = true;
return false;
}
});
if (!is_unhappy) {
ajaxEmailForm();
};
});