I have script like this:
const add_modal = $('#add_modal');
const add_form = $('#add_form');
const add_button = $('#add_button');
const save_button = $('#save_button');
let add_validator = add_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: "/admin/users/check-email",
},
role: {
required: true,
},
password: {
required: true,
minlength: 12,
},
password_verification: {
required: true,
minlength: 12,
equalTo: '#password'
},
},
messages:{
email:{
remote: "Email is already taken."
}
}
});
add_button.click(function (e) {
e.preventDefault();
add_modal.modal("show");
add_validator.resetForm();
$(':input').val("");
$("#csrf").val($csrf);
});
save_button.click(function (e) {
e.preventDefault();
let form = $(this).closest('form');
let $action = form.attr('action');
let $method = form.attr('method');
let $data = form.serialize();
if (add_form.valid()) {
$.ajax({
url: $action,
type: $method,
data:$data,
success: function (result) {
if (result.type === 'success') {
add_modal.modal("hide");
add_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});
it seems like the jqueryvalidation plugin is checking mail availability on modals open. since when I see at web inspector it sends a post request to /admin/users/check-email. how can i prevent this behaviour and make it only check when i press save_button? save_button is a button inside the modal.
Try this:
let update_validator = update_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: {
url: "/admin/users/email-available",
type: "post",
data: {
user_id: function () {
return $("#id").val();
}
}
}
},
role: {
required: true,
},
password: {
minlength: 12
},
password_verification: {
required: isPasswordPresent,
minlength: 12,
equalTo: "#update_password"
},
},
messages:{
email:{
remote: "Email is already taken."
}
},
submitHandler: function(form, event) {
event.preventDefault();
let $action = $(form).attr('action');
let $method = $(form).attr('method');
let $data = $(form).serialize();
$.ajax({
url: $action,
type: $method,
data: $data,
success: function (result) {
if (result.type === 'success') {
update_modal.modal("hide");
update_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
showCloseButton: true
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});
Related
Why is that only the field name shows when i enter invalid formats. Eventhough ive tried different validation styles it still shows if the format is invalid. I've created custom validation already but it only works if the date is empty or null but if it is not it does not work it is because when i enter wrong format in the field the custom validation does not work .
image of the actual validation
here is the code
$('#lot-sched-grid').kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "maintenance/sales/s-lot-sched/read-header/0",
dataType: "json"
},
update: {
url: "maintenance/sales/s-lot-sched/update",
type: "POST",
dataType: "json",
complete: function(jqXhr, textStatus) {
if (textStatus == 'success') {
/*var grid = vm.GRID.init();
grid.dataSource.read();*/
vm.GRID.init().dataSource.read();
swal("Success", "Lot Remarks is successfully updated!", "success");
} else {
vm.error(jqXhr);
}
}
}
},
pageSize: window.uiDefaults.pageSize,
// batch: true,
schema: {
model: {
id: "lot_id",
fields: {
lot_id: { editable: false, nullable: true },
lot_prod_grp_id: { type: "string" },
lot_year: { type: "string", editable: false },
lot_code: { type: "string", editable: false },
lot_start_date: {
type: "date",
parse: function(value) {
return kendo.toString(value, "yyyy-MM-dd");
},
validation: {
custom: function(input) {
if (input.is("[name='lot_start_date']") && input.val().length == 0) {
input.attr("data-custom-msg", "Start date is required.");
return false;
}
return true;
}
}
},
lot_remarks: {
type: "string",
validation: {
lotremarks_min_validate: function (input) {
if (input.is("[name='lot_remarks']") && input.val().length < 4 && input.val().length != 0) {
input.attr("data-lotremarks_min_validate-msg", "Lot Remarks minimum input value is 4.");
return false;
}
return true;
},
lotremarks_max_validate: function (input) {
if (input.is("[name='lot_remarks']") && input.val().length > 100 && input.val().length != 0 ) {
input.attr("data-lotremarks_max_validate-msg", "Lot Remarks maximum input value is 100.");
return false;
}
return true;
},
},
},
}
}
}
}),
scrollable: false,
filterable: window.uiDefaults.filterable,
pageable: window.uiDefaults.pageable,
sortable: window.uiDefaults.sortable,
noRecords: true,
messages: {
noRecords: window.uiDefaults.noRecordsMessage,
},
selectable: "row",
/*save: function(e){
console.log(e);
},*/
editable: true,
toolbar: [ 'save', 'cancel' ],
columns: [
{
field: "lot_code",
title: "Lot Code",
width: 120,
},
{
field: "lot_year",
title: "Year",
width: 100,
},
{
field: "lot_start_date",
title: "Start Date",
format: "{0:yyyy-MM-dd}",
width: 120,
},
{
field: "lot_remarks",
title: "Remarks",
template: kendo.template($('#lot-remarks-template').html()),
}],
});
Try changing the attribute name you're adding.
Change the following:
input.attr("data-custom-msg", "Start date is required.");
To:
input.attr("data-lot_start_date-msg", "Start date is required.");
So what i did is to change the custom validation to date validation , and create a condition inside the validation to determine if it is empty and if ever it is not in its proper format .
this is my first project I want to put the validation on dropdown input field with multiple selection but its not working.Any help would be appreciated.
Here is my code:-
<script type="text/javascript">
$("#formValidate").validate({
rules: {
name: {
required: true,
minlength: 5
},
business: {
required: true,
minlength: 5
},
email: {
required: true,
email:true
},
phone: {
required: true
},
image_consulting: {
required: true
},
soft_skill:{
required: true
},
question: {
required: true,
minlength: 15
},
about_us: true
},
errorElement : 'div',
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error)
} else {
error.insertAfter(element);
}
}
});
</script>
I want the email field to be validated in correct format
function editAccount() {
$("#editacc").validate({
rules: {
email: {
remote: {
url: "../accounts/check-email.php?type=email",
type: "get",
data: {
email: function() {
return $( "#email" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
imeino: {
remote: {
url: "../accounts/check-email.php?type=imeino",
number: true,
type: "get",
data: {
imeino: function() {
return $( "#imeino" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
username: {
remote: {
url: "../accounts/check-email.php?type=username",
type: "get",
data: {
imeino: function() {
return $( "#username" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
mobileno: {
minlength: 10,
number: true
},
accounttype:"accountcheck"
},
messages:{
email: {
email: "Invalid Email Address",
remote: "Email ID Already registered"
},
imeino: {
remote: "IMEI No Exists",
},
username: {
remote: "Username Exists"
},
accounttype:"Imei no required for Agent",
firstname:"Firstname Required",
lastname:"Lastname Required",
mobileno:"Mobile Number Required with numbers",
email:"Email Id Required with valid format!!",
reportingstaff:"Reporting Staff Required"
},
Email is not validating in correct format.
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
}
});
/*************** check-email.php **************/
< ?php
/* check if email is already registered */
//connect to db using mysqli
if (!empty($_POST['email']))
{
$email = $mysqli->real_escape_string($_POST['email']);
$query = "SELECT ID FROM users WHERE user_email = '{$email}' LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>
$("#da-ex-validate2").validate({
rules: {
details: {
required: true,
rangelength: [1, 500]
},
editor1: {
required: true,
minlength: 1
},
title: {
required: true,
rangelength: [1, 100]
},
SlideDeckPhoto: {
required: "#iButton:checked",
accept: ['.jpeg', '.png', '.jpg', '.gif']
},
min1: {
required: true,
digits: true,
min: 5
},
max1: {
required: true,
digits: true,
max: 5
},
submitHandler: function(form) {
$(form).ajaxSubmit();
},
range1: {
required: true,
digits: true,
range: [5, 10]
}
},
invalidHandler: function (form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("#da-ex-val2-error").html(message).show();
} else {
$("#da-ex-val2-error").hide(); // it's not work !!! and the page is reload !!
}
}
});
I would also would like to save my form values to MySql without reload the page .
Please help ! I read so many post and tried so many thing !
If you put a code please tell where to put it ..
BTW my form has few input fields and also an file input field .
PLEASE HELP !
return false from the submit handler
submitHandler: function(form) {
$(form).ajaxSubmit();
return false;
}
This is my solution, put it after invalidHandler :
submitHandler: function(form) {
var dataString = $('#YourFormID').serialize();
$.ajax({
type: 'POST',
url: 'yourpage.php',
data: dataString,
success: function() {
$('#YourErrorDivID').hide();
$('#YourSuccessDivID').html("Your Message").show();
}
});
}
I am validating my form using jquery as below:
jQuery(document).ready(function(){
jQuery('#adminform').validate({
rules: {
name: {
minlength: 5,
maxlength: 30,
required: true
},
username: {
required: true,
minlength: 5,
maxlength: 30
}
},
highlight: function(label) {
jQuery(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
},
messages:{
name: {
required: "Enter your name"
},
username: {
required: "Enter a username"
}
}
});
});
now how should I prevent the form from submission if the rules are not meet?
When I click the submit button nothing should happen.
To stop a form being submitted you use:
return false;
When you know the input is invalid.
Prevent form submission using jQuery?
$('#myFormId').submit(function(event) {
event.preventDefault();
});
OR:
$('#myFormId').submit(function()
{
return false;
});
Prevent the submit event and remain on the screen
e.preventDefault();
what about this?
Your code is perfect just a submit trigger needed : http://jsfiddle.net/uUdWN/
jQuery(document).ready(function() {
jQuery('#adminform').validate({
rules: {
name: {
minlength: 5,
maxlength: 30,
required: true
},
username: {
required: true,
minlength: 5,
maxlength: 30
}
},
highlight: function(label) {
jQuery(label).closest('.control-group').addClass('error');
},
success: function(label) {
label.text('OK!').addClass('valid').closest('.control-group').addClass('success');
},
messages: {
name: {
required: "Enter your name"
},
username: {
required: "Enter a username"
}
}
});
$("#adminform").submit(); // <-------------just triggered submit
});