Why validation is not working in this script ?
I gave blank input but it is not giving the required messsage and also regx is not working.
$(document).ready(function(){
var $form = $(this);
$.validator.addMethod("regx", function(value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid Pan number.");
$("#checkval").validate({ //here is form id #checkval
showErrors: function(errorMap, errorList) {
for (var error in errorMap) {
$.growl.error({ message: errorMap[error] });
}
},
onkeyup: false,
rules: {
oldemail: {
required: true,
regx: /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/
},
newemail: {
required: true,
regx: /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/
}
},
messages: {
oldemail: {
required: "Please enter old e-mail ",
regx: "Please enter your valid e-mail address"
},
newemail: {
required: "Please enter new e-mail ",
regx: "Please enter your valid e-mail address"
}
},
// From here started ajax code.
submitHandler: function(form) {
$.ajax({
url: index.php?act=account,
type: "POST",
data: $(form).serialize(),
success: function(response) {
alert(response);
$('#inquiryFormHolder').html("Your form was submitted!");
// here is div id #inquiryFormHolder
}
});
$form.submit();
}
});
});
Related
TLDR version: I have a custom jquery validation the returns the correct values but the rule is not getting enforced.
I have a custom validation rule that looks like this:
$.validator.addMethod("isDomainValid", function(value, element) {
var domain = value.split("#");
$.get('/api/validate-domain/' + domain[1], function(data, status) {
domain = JSON.parse(data);
console.log(domain['status'] === 'valid');
return (domain['status'] === 'valid');
});
});
This validation calls a PHP API that checks if the email's domain name is live, hence correct. This API returns the correct values and the console.log() also reflects the correct values, which is the value I am returning as a boolean. All good so far...
I call this validation rule like this:
validator.validate({
rules: {
email: {
required: true,
email: true,
isDomainValid: true,
},
});
I also have some custom error messages (I think maybe irrelevant) like the following:
messages: {
email: {
required: "The Email Address cannot be empty",
isDomainValid: "Please correct the Email Address after the # character",
email: "Invalid Email Address format",
}, },
All my validations, including one other custom validation work flawlessly except this one. Here is all the code I am running in case someone wants to see the whole thing. Again, all validations work except the custom isDomainValid validation.
var validator = $('#checkout_form');
$.validator.addMethod("checkPoBox", function(value, element) {
let cleansedValue = $.trim(value.toLowerCase()).replace(/[^a-zA-Z]+/g, '');
let checked = $('#ship-box').prop('checked') ? true : false;
if (/pobox/i.test(cleansedValue) && checked && element.name == 'shipping_address') {
return false;
}
if (/pobox/i.test(cleansedValue) && !checked && element.name == 'billing_address') {
return false;
}
return true;
});
$.validator.addMethod("isDomainValid", function(value, element) {
var domain = value.split("#");
$.get('/api/validate-domain/' + domain[1], function(data, status) {
domain = JSON.parse(data);
console.log(domain['status'] === 'valid');
return (domain['status'] === 'valid');
});
});
validator.validate({
rules: {
email: {
required: true,
email: true,
isDomainValid: true,
},
billing_first_name: {
required: true
},
billing_last_name: {
required: true
},
billing_address: {
required: true,
checkPoBox: true
},
billing_city: {
required: true
},
billing_state: {
required: true
},
billing_zip: {
required: true,
minlength: 5,
maxlength: 5,
digits: true
},
billing_phone: {
required: true,
minlength: 10,
maxlength: 10,
digits: true
},
name_on_credit_card: {
required: true
},
credit_card_number: {
required: true,
creditcard: true
},
expiration_month: {
required: true
},
expiration_year: {
required: true
},
cvv: {
required: true,
minlength: 3,
maxlength: 4,
digits: true
},
shipping_first_name: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_last_name: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_address: {
required: function () {
return $('#ship-box').prop('checked');
},
checkPoBox: true
},
shipping_city: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_state: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_zip: {
required: function () {
return $('#ship-box').prop('checked');
},
minlength: 5,
maxlength: 5,
digits: true
},
shipping_phone: {
required: function () {
return $('#ship-box').prop('checked');
},
minlength: 10,
maxlength: 10,
digits: true
}
},
messages: {
email: {
required: "The Email Address cannot be empty",
isDomainValid: "Please correct the Email Address after the # character",
email: "Invalid Email Address format",
},
billing_first_name: "First Name cannot be blank",
billing_last_name: "Last Name cannot be blank",
billing_address: {
required: "Address cannot be blank",
checkPoBox: "Products cannot be shipped to a P.O. Box"
},
billing_city: "Town/City cannot be blank",
billing_state: "Please select a State",
billing_zip: "Please enter a valid 5 digit Zip Code",
billing_phone: "Please enter a valid 10 digit Phone Number",
name_on_credit_card: "Name on Card cannot be blank",
credit_card_number: "Please enter a valid Credit Car Number",
expiration_month: "Please select an Expiration Month",
expiration_year: "Please select an Expiration Year",
cvv: "Please enter a valid 3 or 4 digit CVV",
shipping_first_name: "First Name cannot be blank",
shipping_last_name: "Last Name cannot be blank",
shipping_address: {
required: "Address cannot be blank",
checkPoBox: "Products cannot be shipped to a P.O. Box"
},
shipping_city: "City cannot be blank",
shipping_state: "Please select a State",
shipping_zip: "Please enter a valid 5 digit Zip Code",
shipping_phone: "Please enter a valid 10 digit Phone Number",
},
invalidHandler: function(event, validator) {
if(validator.numberOfInvalids() > 0) {
event.preventDefault();
$('button#place_order_btn').text("PLACE ORDER");
return false;
}
},
submitHandler: function (validator) {
validator.submit();
}
});
Any help will be greatly appreciated.
I think you're running into a problem where the return value for the success callback function is lost in the $.get method. In my experience I've had to trigger errors manually as part of the callback when checking against the server in a similar way.
Alternatively, I was digging around and found some jQuery Validation documentation that seems like it would make what you are trying to do a little easier: https://jqueryvalidation.org/remote-method/
Try updating the rules.email properties, replacing isDomainValid:
rules: {
email: {
required: true,
email: true,
remote: {
url: function() {
var value = $("[name='email']").val();
var domain = value.split("#");
return "/api/validate-domain/" + domain[1];
},
}
},
You can remove the call to $.validator.addMethod that registers the "isDomainValid" method.
Also, don't forget to update isDomainValid elsewhere, replacing it with remote so the messages are correct.
messages: {
email: {
required: "The Email Address cannot be empty",
email: "Invalid Email Address format",
remote: "Please correct the Email Address after the # character",
},
I found this question being asked before and saw the recommendation was to add a method called alphanumeric. I tried adding this method, but the validation will still not accept phone numbers with dashes.
Does anyone see what I am doing wrong?
$('#phone').keyup(function() {
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
}, "Numbers and dashes only");
});
$('#salesforce_submit').validate({
rules: {
phone: {
required: true,
//digits: true,
minlength: 10,
alphanumeric: true
}
},
messages: {
phone: {
required: "Please enter your phone number",
digits: "Please enter a valid phone number with only numbers",
minlength: "Your number seems a bit short, doesn't it?"
}
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
console.log(data);
if (data == 'Error!') {
alert('Unable to submit form!');
} else {
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" method="POST" enctype="multipart/form-data">
<div><input id="phone" placeholder="Phone*" class="input block" maxlength="12" name="phone" type="phone"></div>
<input type="Submit" Value="Submit">
</form>
You can use this code for allowing numbers and dashes
jQuery.validator.addMethod("numericdashe", function (value, element) {
console.log(value);
if (/^[0-9\-]+$/i.test(value)) {
return true;
} else {
return false;
};
}, "Numbers and dashes only");
add numericdashe role
phone: {
required: true,
//digits: true,
minlength: 10,
//alphanumeric: true
numericdashe: true
}
},
no need add jQuery.validator.addMethod inside keyup listener.
You have problem with your regex.
This regex works: /^[+][(]{0,1}[0-9]{1,3}[)]{0,1}[-\s./0-9]$/i
working fiddle
$('#phone').keyup(function() {
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/i.test(value);
}, "Numbers and dashes only");
});
$('#salesforce_submit').validate({
rules: {
phone: {
required: true,
//digits: true,
minlength: 10,
alphanumeric: true
}
},
messages: {
phone: {
required: "Please enter your phone number",
digits: "Please enter a valid phone number with only numbers",
minlength: "Your number seems a bit short, doesn't it?"
}
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
console.log(data);
if (data == 'Error!') {
alert('Unable to submit form!');
} else {
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" method="POST" enctype="multipart/form-data">
<div><input id="phone" placeholder="Phone*" class="input block" maxlength="12" name="phone" type="phone"></div>
<input type="Submit" Value="Submit">
</form>
Hi have a form where I have applied the jquery validation plugin. Everything works well until I come to submit the form. What the form does is that it checks the username and email address to what is stored in the database and if the username or email is taken, an error message is displayed. This is done when the form element loses focus.
So what I do is I change the username to a username that is stored in the db and an error message is returned, which is correct. I then change the username to a unique value and the error message disappears.
Now when I come to submit the form, an error message is displayed on the username that is not unique.
so if I change my username to be ericy#sa2 error is displayed, I change to danny#sa which removes the error and then when I submit the form the error message pops up that ericy#sa2 is not unique and clearly the form element contains danny#sa
Here is my jQuery code
$(document).ready(function(){
$( "#manageAdministratorForm" ).validate({
onkeyup: false, //turn off auto validate whilst typing
rules: {
"name": "required",
"menuAccess[]": "required",
email: {
required: true,
email: true,
remote: {
url: "index.php?action=MANAGE_ADMINISTRATORS_FORM",
type: "post",
data: {
email: function(){
return $('#email').val();
},
adminId: function() {
return $('#adminId').val();
},
subAction: "validateEmail"
}
}
},
username: {
required: true,
remote: {
url: "index.php?action=MANAGE_ADMINISTRATORS_FORM",
type: "post",
data: {
username: function(){
return $('#username').val();
},
adminId: function() {
return $('#adminId').val();
},
subAction: "validateUsername"
}
}
},
newPassword: {
minlength: 8
},
confirmPassword: {
equalTo: "#newPassword"
}
},
messages: {
"name": "A name must be entered for the administrator",
"menuAccess[]": "Menu items must be assigned to an administrator",
"username": {
required: "A username must be entered for the administrator",
remote: function() { return $.validator.format("Username {0} is already taken", $("#username").val())}
},
"email": {
required: "An email must be entered for the administrator",
email: "Please enter a valid email address",
remote: function() { return $.validator.format("Email {0} is already taken", $("#email").val())}
},
"newPassword": {
minlength: "Enter at least {0} characters for your password"
},
"confirmPassword": {
equalTo: "Please enter the same password as above"
}
},
errorContainer: $('#errorContainer'),
errorLabelContainer: $('#errorContainer ul'),
wrapper: 'li',
submitHandler: function(form) {
var $form = $(form);
$form.submit();
}
});
});
I have to submit a form inside the Ajax.
I'm receiving 'form.submit is not a function' JQuery error.
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: function(data) {
if(data == "true") {
form.submit(); // It shows form.submit is not a function
} else {
// Displays error
}
}
});
}
});
When I give the form.submit() function above the Ajax, It works!
Then how do I submit this form inside the Ajax success function?
Hey u can use the arrow function feature here
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: (data) => {
if(data == "true") {
form.submit();
} else {
// Displays error
}
}
});
}
});
It will bind the context of the callback function to submitHandler function
try changing the scope of the form variable:
var form_to_be_submitted = null;
$("#form").validate({
// Specify the validation rules
rules: {
type: "required",
groups: {
required: true
}
},
// Specify the validation error messages
messages: {
type: "Type is required",
groups: {
required: "Group is required"
}
},
submitHandler: function(form) {
form_to_be_submitted = form;
$.ajax({
type: "POST",
url: "check_exists.php",
data: {
groups: $( "#groups" ).val(),
type: $( "#type" ).val()
},
success: function(data) {
if(data == "true") {
form_to_be_submitted.submit(); // It shows form.submit is not a function
} else {
// Displays error
}
}
});
}
});
Here I am using jQuery validation. It is working fine, after fill all form fields I want do Ajax call but I am not able to do that. I am getting error. How can I do?
jQuery(document).ready(function(){
jQuery("#SubmitForm").validate({
rules: {
"address": {
required: true
},
"username": {
required: true
},
"mobileNumber": {
required: true,
number: true,
minlength : 12
},
"userEmailid": {
required: true,
email: true
},
"message": {
required: true
}
},
messages: {
"address": {
required: "Please enter your Location."
},
"username": {
required: "Please enter your Fullname."
},
"mobileNumber": {
required: "Please enter your Mobile Number."
},
"userEmailid": {
required: "Please enter your Email.",
email: "Please enter valid Email."
},
"message": {
required: "Please enter Message."
}
},
/* jQuery.ajax({
type:'POST',
url :"php/submit_hitachiForm.php",
data: jQuery('form#SubmitForm').serialize(),
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "success"){
$("#success_message").show();
$("#success_message").fadeOut(4000);
}
},
error:function(exception){
alert('Exeption:'+exception);
}
}); */
});
});
Put all the validation:
$('#SubmitForm).validate({
// validation rules
});
and after that initialize the validation function like:
if($('#SubmitForm).valid())
{
// make ajax() call here
}
Try this in your code
submitHandler: function() {
/*ajax request*/
}