Validation gets removed from SSN textbox after calling event.preventDefault(); in $("form").submit(function (event)
Validation gets fired and than removed
function CheckSSN() {
var sender = $("#SSN");
var value = $(sender).val();
var errorSpan = $(sender).siblings("span[data-valmsg-for='SSN']");
var message = "SSN is required.";
var validAliasPatt = /^[0-9]{9}$/;
if (!value || value == "" || value == null) {
enableValidationUI(sender, errorSpan, message);
return false;
}
else if (!validAliasPatt.test(value)) {
message = "SSN should be a 9 digit number.";
enableValidationUI(sender, errorSpan, message);
return false;
}
else {
disableValidationUI(sender, errorSpan);
return true;
}
}
----------
("form").submit(function (event) {
var submit = true;
if (!CheckSSN()) {
event.preventDefault();
var submit = false;
}
if (submit) {
$("form").submit();
}
else {
event.preventDefault();
return;
}
});
The issue was with using ("form").submit(function (event) which ended up creating endless loop. After changing to ('button').click fixed this issue.
Related
We have a Shopify store and i have a script which validates the email adress and writes out if the email address is not good, another script is checking if the form is filled out and if it's not - it's not letting the customer to pass the next stage based on ID selector.
I only need this email validator to do the same thing as the other script, write out an alert when the email address is not correct and don't let them pass to the next step.
Can someone help with this? How to do that?
Script which validates the email address:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
if (validateEmail(email)) {
$result.text(email + ' e-mail address is valid!');
$result.css('color', 'green');
} else {
$result.text(email + ' Lūdzu, ievadiet derīgu e-pastu lai pabeigt pirkumu');
$result.css('color', 'red');
}
return false;
}
$('#email').on('input', validate);
Script which checks wheter the form was filled out or not:
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
})
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
}
};
Appreciate the help, what i'm missing here?
Thank you!
Use the email validation inside on onClick event like this and set the var allAreFilled false is email validation failed
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
});
/* Here email valdation */
const email = $('#email').val();
if( !email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)){
allAreFilled = false;
}
/* terms and condtions check */
if( !$('#CartTermsDrawer').is(':checked') ){
allAreFilled = false;
}
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
return;
}
};
I am able to get the information from the object I am using to store the form information, when the one tries to fire the submit without filling in the fields successfully, but when I enter all the information correctly I can't seem to obtain the same upon success?
var theForm = document.getElementsByTagName('form')[0];
var firstNameInput = document.getElementById('firstNameInput');
var lastNameInput = document.getElementById('lastNameInput');
var emailInput = document.getElementById('emailInput');
var stateInput = document.getElementById('stateInput');
var theButton = document.querySelector('input[type=submit]');
// Wire the form's submit event to a callback
theForm.addEventListener('submit', validate);
function validate(e) {
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var formData = {
'firstName': null,
'lastName': null,
'email': null,
'stateInput': null
}
if ((firstNameInput.value == '') || (firstNameInput.value == null)) {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if ((lastNameInput.value == '') || (lastNameInput.value == null)) {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if ((stateInput.value == 'selectstate')) {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
console.log('There is no data from the form: ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return false;
} else {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
console.log('There is now data from the form: :) ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return true;
}
}
I tried this:
var result = theForm.addEventListener('submit', validate);
if (result) {
console.log(result);
}
Any help would be appreciated!
According to w3schools.com, this function, addEventListener() does not return anything.
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
If you'd like to know if the event listener is installed properly, you need to check if the function exists:
if(theForm.addEventListener){
theForm.addEventListener('submit', validate);
}else{
theForm.attachEvent('onclick', validate);
}
I'm building validation for form fields for a form. So, I need to do a validation which I do like this :
$(document).ready(function() {
$('#submitbutton').click(function() {
if (validateField()) {
$('form.checkout_form_validate').submit(function(event) {
return true;
});
}
else {
$('form.checkout_form_validate').submit(function(event) {
event.preventDefault();
return false;
});
}
});
function validateField() {
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var shipping_address = $('#shipping_address_1').val();
var city = $('#city').val();
var state = $('#state').val();
var phone = $('#phone').val();
if (first_name == "" || last_name == "" || shipping_address == "" || city == "" || state == "" || phone == "") {
$('#errorcontainer').html('Fill out all the required fields <br/>');
$('#errorcontainer').fadeIn('fast');
return false;
} else {
return true;
}
}
});
So, If a user just press the submit button, it will throw an error and Form will not submit, But, If after doing this, the user fills out the entire form and then hit submit, Nothing will happen even when validateField() is true.
How to "reset" it? Any ideas ?
On each click on submit button, you are binding new form submit
handler. Don't nest events...
You validation logic should be:
$(function() {
$('form.checkout_form_validate').submit(function(event) {
return validateField();
});
});
function validateField() {
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var shipping_address = $('#shipping_address_1').val();
var city = $('#city').val();
var state = $('#state').val();
var phone = $('#phone').val();
if (first_name == "" || last_name == "" || shipping_address == "" || city == "" || state == "" || phone == "") {
$('#errorcontainer').html('Fill out all the required fields <br/>');
$('#errorcontainer').fadeIn('fast');
return false;
} else {
return true;
}
}
You don't need e.preventDefault(); and a return false; statement, they do the same thing
return false within a jQuery event handler = e.preventDefault() and e.stopPropagation()
I'm trying to stop my form from submitting when the confirmation message is cancelled, but how can I cancel my form’s submission from inside the each()?
$('#myForm').submit(function() {
var inputs = $(this).find('input:checked');
inputs.each(function() {
var inputId = $(this).attr('id');
if(inputId != undefined && inputId.substring(0, 8) == 'inputName') {
var r = confirm("Are you sure you want to continue?");
if (r == true) {
return true;
} else {
// This doesn't stop the form submit
return false;
}
}
});
return true;
});
You can use the event argument that’s passed to event listeners instead; it has a method named preventDefault() that stops the default action from being performed.
$('#myForm').submit(function (e) {
var inputs = $(this).find('input:checked');
inputs.each(function () {
var inputId = this.id;
if (inputId != undefined && inputId.substring(0, 8) == 'inputName') {
var r = confirm("Are you sure you want to continue?");
if (!r) {
e.preventDefault();
}
}
});
});
I want after click on button(Click Me), validation check just for field 2-1 and field 2-2 no for all files that has class .required (... .closest('form')...), how is it in my code?
DEMO: (in here when that you click on button it work for all field that have class .required but i want just check field into form closest('form')): http://jsfiddle.net/ZsPyy/2/
function required_valid() {
var result = true;
$('.required').each(function () {
if (!$(this).val()) {
//var cssObj=;
$(this).css("background", "#ffc4c4");
result = false;
}
$(this).keyup(function () {
$(this).css("background", "#FFFFEC");
})
});
return result;
}
$('button').live('click', function (e) {
e.preventDefault();
var passed = true;
//passed = required_selectbox() && passed;
passed = required_valid() && passed;
if (!passed) {
return false;
}
});
Try this code: http://jsfiddle.net/ZsPyy/4/
I have passed the button to the required_valid function. So we can get the btn's parent form.
function required_valid(btn) {
var result = true;
$(btn).closest("form").find('.required').each(function () {
if (!$(this).val()) {
//var cssObj=;
$(this).css("background", "#ffc4c4");
result = false;
}
$(this).keyup(function () {
$(this).css("background", "#FFFFEC");
})
});
return result;
}
$('button').live('click', function(e) {
e.preventDefault();
var passed = true;
//passed = required_selectbox() && passed;
passed = required_valid(this) && passed;
if (!passed) {
return false;
}
});
function required_valid(sbtn) {
var result = true;
$(sbtn).closest("form").children('.required').each(function () {
if (!$(this).val()) {
//var cssObj=;
$(this).css("background", "#ffc4c4");
result = false;
}
$(this).keyup(function () {
$(this).css("background", "#FFFFEC");
})
});
return result;
}
$('button').live('click', function(e) {
e.preventDefault();
var passed = true;
//passed = required_selectbox() && passed;
passed = required_valid(this) && passed;
if (!passed) {
return false;
}
});