I have a simple form I'm making client side validation for.
To validate, none of the fields should be left blank.
This is how I go at it:
function validateForm() {
$('.form-field').each(function() {
if ( $(this).val() === '' ) {
return false
}
else {
return true;
}
});
}
For some reason, my function always returns false, even though all fields are filled.
You cannot return false from within the anonymous function. In addition, if it did work, you would return false if your first field was empty, true if not, and completely ignore the rest of your fields. There may be a more elegant solution but you can do something like this:
function validateForm() {
var isValid = true;
$('.form-field').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
return isValid;
}
Another recommendation: this requires you to decorate all of your form fields with that formfield class. You may be interested in filtering using a different selector, e.g. $('form.validated-form input[type="text"]')
EDIT Ah, I got beat to the punch, but my explanation is still valid and hopefully helpful.
You were returning from the inner function not from the validate method
Try
function validateForm() {
var valid = true;
$('.form-field').each(function () {
if ($(this).val() === '') {
valid = false;
return false;
}
});
return valid
}
function validateForm() {
var invalid= 0;
$('.form-field').each(function () {
if ($(this).val() == '') {
invalid++;
}
});
if(invalid>0)
return false;
else
return true;
}
Here is a similar approach:
function validateForm() {
var valid = true;
$('.form-field').each(function() {
valid &= !!$(this).val();
});
return valid;
}
!! just converts input value to bool
Related
I am new to JavaScript and I have written the code below, which is supposed to be taking the input of a form field (in that case of the lastname) and in case it is empty, it will not allow me to be redirected to next page. However, it doesnt work.. Does anybody know why or how I could fix it? Thank you in advance!
window.addEventListener("DOMContentLoaded", init, false);
function init() {
var form = document.querySelector("form");
form.addEventListener("submit",
function(e) {
validate(e);
e.stopPropagation();
if (invalid == true) e.preventDefault();
},
false);
var invalid = false;
function validate(e) {
var lname = document.getElementById("lastName");
invalid = testField(lname);
return invalid;
}
function testField(field) {
if (field.value == undefined || field.value == " ")
invalid = true;
else
invalid = false;
return invalid;
}
}
}
This is wrong:
if (field.value == undefined || field.value == " ")
You're comparing the value to a string containing a single space. If the field is empty, it won't match this.
There's also no need to compare with undefined, the value is always defined.
So it should be:
if (field.value == "")
You might want to trim the field first, in case they just type a bunch of spaces:
if (field.value.trim() == "")
The main problem is making a comparison against ' ' space. That's not correct because you want to validate whether that value is empty.
So, you need to compare as follow: field.value.trim() === ""
Good, I think your code could be reformatted, for example you don't need to compare boolean values, they are already a boolean, so you can use them directly in your conditions, i.e:
if (invalid == true) //See? the invalid variable is a boolean.
So, use it as follow:
if (invalid)
Another potential code to be reformatted:
//Here you want to evaluate and assign a boolean, well you just have to assign the result of that condition.
function testField(field) {
if (field.value == undefined || field.value == " ")
invalid = true;
else
invalid = false;
return invalid;
}
Do the following:
function testField(field) {
return invalid = field.value == undefined || field.value == " ";
}
And finally, this code doesn't need that global variable invalid, so you can remove the invalid variable:
function(e) {
validate(e);
e.stopPropagation();
if (invalid == true) e.preventDefault();
}
Access that function as follow:
function(e) {
e.stopPropagation();
if (validate(e)) e.preventDefault();
}
Your code after be reformatted:
window.addEventListener("DOMContentLoaded", init, false);
function init() {
var form = document.querySelector("form");
form.addEventListener("submit",
function(e) {
e.stopPropagation();
if (validate(e)) e.preventDefault();
},
false);
function validate(e) {
var lname = document.getElementById("lastName");
return testField(lname);
}
function testField(field) {
return field.value === undefined || field.value.trim() === ""
}
}
See?, now your code is cleaner.
There are some pieces of your code to be reformatted, but this is a good start.
I want the form to post the credentials via a get request but have difficulties making it work together with the onsubmit parameter which is used to validate the data entered. This is my form code:
<form onsubmit="return formValidation()" action="show_get.php" method="get" name="registration">
This is the code I used for validation
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
{
if (allLetter(name)) {
if (ValidateEmail(uemail)) {
if (checkDate()) {
}
}
}
return false;
}
}
function allLetter(name) {
var letters = /^[A-Za-z]+$/;
if (name.value.match(letters)) {
return true;
}
else {
alert('Name must have alphabet characters only');
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
}
}
If you attach an onsubmit event handler and it returns false, the form will not be submitted. In your case, that always happens, even if the input is valid.
You check allLetter(), then ValidateEmail() and checkDate(), but you don't return true when they're all valid. Your code continues and it reaches return false;. The submit event handler returns the result of that validation function (which is false), so it returns false too. This tells the form to not submit.
Change your validation function to this:
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
if (allLetter(name) && ValidateEmail(uemail) && checkDate()) {
return true;
} else {
return false;
}
}
If all three checks return true, the validation function will return true as well and the form will be submitted.
Note: You had one unnecessary pair of brackets ({}), I removed them. I also improved readability by combining all the nested if statements into one.
Edit: Also, your checkDate() doesn't return true and false accordingly. It returns undefined by default, which is a falsy value. This means that it won't pass the validation function's && check and the form won't get submitted. Change checkDate() to this:
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
} else {
return true;
}
}
Edit 2: You also incorrectly get the values of your input elements. When you do this:
var name = document.registration.name;
var uemail = document.registration.email;
You get the HTML element with name attribute name and HTML element with name attribute email. You should get the elements' values:
var name = document.registration.name.value;
var uemail = document.registration.email.value;
It's best to edit your answer and add the full HTML and JavaScript. There might be more problems.
I am working a simple form validation and I have 3 functions where I check the input text fields, a select field and 2 radio buttons. For each group I have made a function, so 3 functions.
I have tested the functions on its own and they are working. But if I use them all 3 together at the end of my script, only one of them works.
Can anyone tell me what I need to do?
// Form validation
$(function() {
function wz_validation() {
var ok = true;
$('input[validate="true"]').each(function() {
if($(this).val() == '') {
ok = false;
$(this).addClass('red_border');
}
else $(this).removeClass('red_border');
});
return ok;
}
// Check Bank select box on checkout page
function wz_val_select() {
if($(".payment select")) {
if($(".payment select option:selected").val() == "") {
$(".payment select").addClass('red_border');
return false;
}
else{
$(".payment select").removeClass('red_border');
return true;
}
}
}
function wz_radio_shipping() {
var form = $("#shipping_form");
if(form.length) {
if(form.find('input[name=wz_shipping]:checked').length == 0) {
$("#checkout_shipping").addClass('red_border');
return false;
}
else{
$("#checkout_shipping").removeClass('red_border');
return true;
}
}
}
var wz_form = $('#wz_form1, #wz_form2, #wz_form3, #wz_form7');
$(wz_form).submit(function() {
return wz_validation() && wz_radio_shipping() && wz_val_select();
});
});
&& is a short circuit operator. It prevents the evaluation of b in a && b when a is falsy.
If you want to have all three functions called even when some of them return false, and if you only return boolean values, use &. As & makes 0 or 1, you might want to convert the result to a boolean with !! :
return !!(wz_validation() & wz_radio_shipping() & wz_val_select());
You might also want to write it more explicitly :
$(wz_form).submit(function(e) {
var good = true;
good &= wz_validation();
good &= wz_radio_shipping();
good &= wz_val_select();
if (!good) e.preventDefault();
});
I'm trying to loop form to check for empty field and then execute and function. I'm currently using something like this below that I found on this website but what is happening that the each loop check 1 field and see 1 that not empty and still execute else function. I think I need to check all at once then execute next function. How could I achieve this?
if($('.enter-info--ownerInfo .req').val() != "") {
alert("Empty Fields!!")
} else {
run this function
}
Thanks...
Use filtering, it is easy:
var anyFieldIsEmpty = $("form :input").filter(function() {
return $.trim(this.value).length === 0;
}).length > 0;
if (anyFieldIsEmpty) {
// empty fields
}
DEMO: http://jsfiddle.net/Lz9nY/
$('.enter-info--ownerInfo .req').each(function() {
if ($(this).val() == "")
{
alert("empty field : " + $(this).attr('id'));
}
});
Start by selecting all your fields:
var fields = $('.enter-info--ownerInfo .req')
Then filter them down to the ones with an empty value:
fields.filter(function() {
return this.value === '';
});
Then check the length property of the resulting object. If it's equal to 0 then all fields have a value, otherwise you execute your function.
if(fields.length === 0) {
// no empty fields
}
else {
// empty fields
}
You can use a loop and flag:
var valid = true;
$('.req').each(function () {
if ($(this).val() == '') {
valid = false;
return false;
}
});
if (valid) {
// all fields are valid
}
You can use .filter method to reduce the elements to those matching your criteria:
if $('.enter-info--ownerInfo .req').filter(function () {
return $.trim($(this).val()) == ""
}).length > 0) {
alert("One or more fields are empty")
} else {
// run this function
}
I am doing a client side form validation to check if passwords match. But the validation function always returns undefined.
function validatePassword(errorMessage)
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
if(password.value)
{
// Check if confirm_password matches
if(password.value != confirm_password.value)
{
return false;
}
}
else
{
// If password is empty but confirm password is not
if(confirm_password.value)
{
return false;
}
}
return true;
}
Please note that the validatePassword is called from a member function of the Form object.
function Form(validation_fn)
{
// Do other stuff
this.submit_btn = document.getElementById("submit");
this.validation_fn = validation_fn;
}
Form.prototype.submit = funciton()
{
var result;
if(this.validation_fn)
{
result = this.validation_fn();
}
//result is always undefined
if(result)
{
//do other stuff
}
}
You could simplify this a lot:
Check whether one is not empty
Check whether they are equal
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
You could wrap your return value in the Boolean function
Boolean([return value])
That'll ensure all falsey values are false and truthy statements are true.
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. #pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean