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.
Related
I have always used jQuery validate() for forms, but have run into a problem recently after an upgrade to our XMPie software (we do targeted communications).
The new version of XMPie requires jQuery 1.10.2 which is a version not supported by validate(), so I'm doing the validation manually.
I can easily validate by writing a separate function for each input, but it means re-writing at least some of the code to target a specific input name or id for example.
What I'm wondering is why can't I write a generic function for a specific input type (for example a simple text field) and let the input call the function on focusout(), passing itself as a parameter?
If I've got two text inputs, "fullName" and "userName" why can't I use
$(document).ready(function () {
var inputName = "";
var inputValue = "";
var inputAlert = "";
$("input").focusout(function () {
inputIdentify(this);
console.log(inputName);
inputGetValue(this);
console.log(inputValue);
if (this.type == "text") {
console.log("YES");
textValidate(inputName, inputValue);
}
});
function inputIdentify(theInput) {
inputName = theInput["name"];
console.log(inputName);
return inputName;
}
function inputGetValue(theInput) {
inputValue = theInput["value"];
return inputValue;
}
function textValidate(theInput, inputValue) {
console.log(theInput,inputValue);
var letters = /^[A-Za-z ]+$/;
if (inputValue.match(letters)) {
$(theInput).addClass("correct");
return true;
} else {
$(theInput).removeClass("correct");
$(theInput).addClass("incorrect");
// alert('Username must have alphabet characters only');
$(inputName).focus();
return false;
}
}
});
to remove and add simple css classes (coloured border) to indicate the problem fields?
Thanks and regards,
Malcolm
You're not passing the correct arguments to textValidate(). You're passing inputName as the theInput, but textValidate() uses $(theInput) to access the input element. You should pass this as that argument:
textValidate(this, inputValue);
Also, your use of global variables is poor design. Since inputIdentify() and inputGetValue() return values, you should assign the returned value to local variables, instead of having those functions set global variables.
$("input").focusout(function () {
var inputName = inputIdentify(this);
console.log(inputName);
var inputValue = inputGetValue(this);
console.log(inputValue);
if (this.type == "text") {
console.log("YES");
textValidate(this, inputValue);
}
});
function inputIdentify(theInput) {
var inputName = theInput["name"];
console.log(inputName);
return inputName;
}
function inputGetValue(theInput) {
var inputValue = theInput["value"];
return inputValue;
}
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 getting an error while setting global variable flag inside function.
Global variable declaration
var flag = false;
Function to validate textbox
//To validate Product Name field
function Name() {
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
flag = false;
}
else {
$('#productNameError').text('');
flag = true;
}
}
Function to validate quantity
//To validate Product Quantity Field
function Quantity() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
flag = true;
}
else {
$('#productQtyError').text('Enter Quantity of the Product');
flag = false;
}
}
else {
$('#productQtyError').text('Quantity is required');
flag = false;
}
}
//Validation Summary
function validate() {
if (flag == true) {
$('#validationSummary').text('');
return true;
}
else {
$('#validationSummary').text('Please fill out required fields.');
return false;
}
}
I am calling first two functions on onfocusout event of textbox and calling validate() function on button click. The problem which I am facing is: inside the Quantity() flag is not getting set to false. Although the field remains blank,record gets inserted.
if you are getting flag=true in validate() then you may be calling Quantity() first ,it will set flag false then Name() which will set flag to true so It bypassed validate() function.
This is not the correct way, you are trying to achive validation. Consider scenario, when user have entered the correct value in first filed, flag will be set to true with the fact that second field is empty amd form will be submitted and hold true vice versa.
If want to achive by this way, keep as many flag variables as the number of fields amd chech all those variable inside validate.
Or, use '.each' to iterate each element and validate it and keep appending validation mesages to dom object.
Thanks
Don't use Global Variables
You're going to have a bad time if you use global variables, you can use the revealing module pattern to encapsulate some of the messiness
Would suggest something like this :
var app = app || {};
app.product = app.product || {};
app.product.validate = app.product.validate || {};
app.product.validate.isValid = false;
app.product.validate.name = function(){
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
app.product.validation.flag = false;
} else {
$('#productNameError').text('');
app.product.validation.flag = true;
}
}
app.product.validate.quantity = function() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
app.product.validate.flag = true;
} else {
$('#productQtyError').text('Enter Quantity of the Product');
app.product.validate.flag = false;
}
} else {
$('#productQtyError').text('Quantity is required');
app.product.validate.flag = false;
}
}
console.log is Your Friend
Try putting a console.log inside some of those methods, what I am guessing your issue is is that something is being called out of the order you expect and setting the flag to a value you aren't expecting.
Can do console.log statement like this console.log if you open up your developer console should show you the output from the console
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
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
}