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()
Related
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);
}
After refreshing the page the label contenct vanishes.
What should i change so that this won't happen?
var versuche = 3; //login attempts
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username == "DjolePhillip" && password == "passwort12345")
{
alert ("Login erfolgreich");
window.location = "loggedin.html";
document.getElementById("loginname").innerHTML = username; //label gets the username
return false;
}
else{
versuche --;
alert("Du hast "+versuche+" uebrig;");
if( versuche == 0)// if no attempts left
{
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
<div id="anmeldung">
<center id="anmeldename"><label id="loginname"></label></center>
</div>
There above is the full Code.
You have to persist the data somewhere. Server side with an ajax request, client side with SessionStorage or LocalStorage.
Example with LocalStorage
var localStorage = window.localStorage
var storedUsername = getUsernameInMemory()
var domUsername = getUsernameDomValue()
var username = storedUsername || domUsername || 'unknown'
if ( !isUsernameDefinedInDOM() ) {
setLoginname(username)
}
if ( isUsernameKnown() && !isUsernameDefinedInLocalStorage() ) {
storeUsername(username)
}
function isUsernameKnown () {
return username !== 'unknown'
}
function setLoginname (_username) {
document.getElementById('loginname').innerHTML = username
}
function storeUsername (_username) {
localStorage['username'] = _username
}
function getUsernameDomValue () {
return document.getElementById('username').value
}
function getUsernameInMemory () {
return localStorage['username']
}
function isUsernameDefinedInDOM () {
return !!getUsernameDomValue() // returns a boolean
}
function isUsernameDefinedInLocalStorage () {
return getUsernameDomValue() !== 'unknown'
}
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.
If statements are being executed but result are not shown, result text is displayed for a fraction of a second and is quickly erased by another result
<script>
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
function myFunction() {
var user = $('#user-name').val();
var userpass = $('#user-password1').val();
var userpass1 = $('#user-password2').val();
var useremail = $('#user-email').val();
var passMatch = false;
var nameValid = false;
var emailValid = false;
//Check Username availability
if ($.trim(user) != '') {
$.post('includes/checkUserName.php', {
checkUser: user
}, function(checkData) {
$('#regErrors').text(checkData);
});
}
//Check Email availability
if ($.trim(useremail) != '') {
$.post('includes/checkEmail.php', {
checkE: useremail
}, function(checkEmail) {
$('#regErrors').text(checkEmail);
});
}
if ($.trim(userpass) != userpass1) {
$('#regErrors').text("Passwords must match")
}
if ($.trim(user) == '' || $.trim(userpass) == '' || $.trim(userpass1) == '' || $.trim(useremail) == '') {
$('#regErrors').text("All fields required")
}
}
</script>
You are replacing the content upon each post by using the .text() method, append a tag instead:
$('#regErrors').append($("<p />", {html: checkData}));
$('#regErrors').append($("<p />", {html: checkEmail}));
$('#regErrors').append($("<p />", {html: "Passwords must match"}));
$('#regErrors').append($("<p />", {html: "All fields required"}));
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();
}
}
});
});