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>
Related
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,
});
}
},
})
}
});
this is form validation, it works awesome then how to validate email pattern matching & phone no. matching. Below is my scipt part... Please Help
<script type="text/javascript">
$(window).load(function(){
$(document).ready(function () {
$('#myform').validate({
rules: {
name: {
required: true
},
email: {
required: true
},phone: {
required: true
},captcha: {
required: true
},
},
errorPlacement: function(){
return false;
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
});
});
</script>
Use this :
$(function() {
$( "#myform" ).validate({
rules: {
name: {
required: true
},
phone: {
required: true,
phoneUK: true //or look at the additional-methods.js to see available phone validations
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name."
},
phone: {
required: "Please enter your phone number."
},
email: {
required: "Please enter your email address."
}
},
});
});
</script>
Use
jQuery.validator.addMethod("foo", function(value, element) {
return this.optional(element) || /^[A-Za-z0-9\w]{4,20}/.test(value);
}, "Your entered data is not phone no");
In Function
"phone": {
required: true,
foo: true
}
See: http://jqueryvalidation.org/jQuery.validator.addMethod/
I have some issues with JQuery. I wrote application with one index file for each component like: account, admin etc. In each index.php I check for action variable and include some other php files or forms. For some forms my validate code works fine for others not.
As an example I will give you two files in account component:
account_register: (not working one)
<script>
// Required
$().ready(function() {
$('<span style="color:red;">*</span>').insertAfter('.required');
});
$().ready(function(){
$("#login_form").validate({
rules: {
login: {
"required"
},
password: {
"required"
}
},
errorElement: "span",
errorPlacement: function(error, element) {
error.insertAfter(element);
}
});
});
and working one:
account_register.php:
<script>
// Required
$().ready(function() {
$('<span style="color:red;">*</span>').insertAfter('.required');
});
// register_form geburtsdatum date
$().ready(function(){
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: "-100:+0",
dateFormat: 'yy-mm-dd'
});
});
// register_form validate
$().ready(function(){
$("#register_form").validate({
rules: {
login: {
required: true,
remote: "validate_register_login.php"
},
name: "required",
vorname: "required",
sex: "required",
geburtsdatum: {
required: true,
date: true
},
golfclub: {
required: true
},
handicap: {
required: true,
number: true
},
password_1: {
required: true,
minlength: 6
},
password_2: {
required: true,
equalTo: "#password_1",
minlength: 6
},
email: {
required: true,
email: true,
remote: "validate_register_email.php"
}
},
messages: {
handicap: "Geben Sie bitte einen Punkt ein !",
login: {
remote: jQuery.format("{0} is already in use")
},
email: {
remote: jQuery.format("{0} is already in use")
}
},
errorElement: "span",
errorPlacement: function(error, element) {
if (element.attr('type') === 'radio') {
error.insertAfter(
element.siblings('input[type="radio"][name="' + element.attr('name') + '"]:last'));
}
else {
error.insertAfter(element);
}
}
});
});
Any idea what can be wrong?
Your format is invalid....
rules: {
login: {
"required" // <- invalid - cannot enclose this in braces
},
password: {
"required" // <- invalid - cannot enclose this in braces
}
}
Only key: value pairs go inside braces; and comma separated when more than one pair,
{
key: value,
key: value,
....
}
So you can do it like this...
(notice the configuration of braces and key: value pairs)
rules: {
login: "required",
password: "required"
}
or long-hand like this...
(again, notice that you still have key:value pairs, but this time, the value's themselves are additional key:value pairs)
rules: {
login: {
required: true
},
password: {
required: true
}
}
In the working one you gave
login: {
required: true,
But in not working you gave
login: {
"required"
I believe required:true is the valid. You can easily figure this out in console as said in the previous comment.
$("#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
});