function that checks if validation is true, then do this - javascript

I'm trying to make this work.
JS validation:
function validation() {
var fname = document.getElementById('fname').value;
if (fname == '') {
document.getElementById('fn').innerHTML = 'Please enter first name.';
}
var lname = document.getElementById('lname').value;
if (lname == '') {
document.getElementById('ln').innerHTML = 'Please enter last name.';
}
var birth = document.getElementById('birthdate').value;
if (birth == '') {
document.getElementById('bday').innerHTML = 'Please enter birthdate.';
}
var gender = document.getElementById('gender').value;
if (gender == 'select') {
document.getElementById('gndr').innerHTML = 'Please choose your gender.';
}
var username = document.getElementById('username').value;
if (username == '') {
document.getElementById('usr').innerHTML = 'Please enter username.';
}
var email = document.getElementById('email').value;
if (email == '') {
}
var econf = document.getElementById('econf').value;
if (econf == '') {
document.getElementById('rt-eml').innerHTML = 'Please confirm your email.';
}
if (econf != email) {
document.getElementById('rt-eml').innerHTML = 'Email did not match.';
}
var password = document.getElementById('password').value;
if (password == '') {
document.getElementById('pass').innerHTML = 'Please enter password.';
}
var pconf = document.getElementById('pconf').value;
if (pconf == '') {
document.getElementById('rt-pass').innerHTML =
'Please confirm your password.';
}
if (pconf != password) {
document.getElementById('rt-pass').innerHTML =
'Password did not match. Try again. ';
}
}
I want my check function to check if validation is true then change the innerHTML of success to You have successfully created an account.
JS check function:
function check() {
if (validation === true) {
document.getElementById('success').innerHTML =
'Your account has been successfully created.';
}
}
I know it's kinda messed up and I admit I'm still new to this.

A common way to do it is to initialize a boolean to true, if any field is empty or not valid then you assign false to this boolean. You return its value at the end of the validation function.
function check() {
//no need to check === true here
if (validation()) {
document.getElementById('success').innerHTML =
'Your account has been successfully created.';
}
}
function validation() {
let isValid = true;
var fname = document.getElementById('fname').value;
if (fname == '') {
document.getElementById('fn').innerHTML = 'Please enter first name.';
isValid = false;
}
var lname = document.getElementById('lname').value;
if (lname == '') {
document.getElementById('ln').innerHTML = 'Please enter last name.';
isValid = false;
}
var birth = document.getElementById('birthdate').value;
if (birth == '') {
document.getElementById('bday').innerHTML = 'Please enter birthdate.';
isValid = false;
}
var gender = document.getElementById('gender').value;
if (gender == 'select') {
document.getElementById('gndr').innerHTML = 'Please choose your gender.';
isValid = false;
}
var username = document.getElementById('username').value;
if (username == '') {
document.getElementById('usr').innerHTML = 'Please enter username.';
isValid = false;
}
var email = document.getElementById('email').value;
if (email == '') {
isValid = false;
}
var econf = document.getElementById('econf').value;
if (econf == '') {
document.getElementById('rt-eml').innerHTML = 'Please confirm your email.';
isValid = false;
}
if (econf != email) {
document.getElementById('rt-eml').innerHTML = 'Email did not match.';
isValid = false;
}
var password = document.getElementById('password').value;
if (password == '') {
document.getElementById('pass').innerHTML = 'Please enter password.';
isValid = false;
}
var pconf = document.getElementById('pconf').value;
if (pconf == '') {
document.getElementById('rt-pass').innerHTML =
'Please confirm your password.';
isValid = false;
}
if (pconf != password) {
document.getElementById('rt-pass').innerHTML =
'Password did not match. Try again. ';
isValid = false;
}
return isValid;
}

Related

returning and recieving boolean

I need help with returning a boolean value from my validateItems() function. And my addPatrons() function (which calls the validateItems() function) must receive the boolean value returned by validateItems() and store it in a variable named "isValid". Then i need to Check the value of isValid if it is true, then use $('myform').submit(); but if it is false, then display "Patron Not Added!" in the endmessage.
this is what i have so far, its not finished because i am lost. its probably something simple but i am not getting it.
var validateItems = function () {
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if (firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
}
var lastName = $("lastname").value;
if (lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
}
var addpatron = function (validateItems) {
var isValid =
if () {
$("myform").submit();
}
else
if () {
$("endmessage").innerHTML = "Patron Not Added!"
}
}
var validateItems = function() {
var formValid = true
var firstName = $("firstname").value;
$("firstname").focus(); //puts crusor on field
if(firstName == "") {
$("firstnameerror").innerHTML = "Enter First Name"
formValid = false
}
var lastName = $("lastname").value;
if(lastName == "") {
$("lastnameerror").innerHTML = "Enter Last Name"
formValid = false
}
return formValid
}
var addpatron = function(validateItems) {
var isValid = validateItems ()
if (isValid ){
$("myform").submit();
}
else if (){
$("endmessage").innerHTML = "Patron Not Added!"
}
}
You have to change your form element as below
<form onsubmit="return validateAndSubmit();" >...</form>
And use the validate function as below
validateAndSubmit(){
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(invalid) return false; // prevents the form from submitting
else return true; // submits the form
}
EDIT 1
if you don't have to submit the form literally, but only perform an operation on submit you can return false always.
validateAndSubmit(){
event.preventDefault();
let invalid = false;
if(firstName == "") invalid = true;
if(lastName == "") invalid = true;
if(!invalid){
addPatron(); // perform add operation only when form is valid
}
return false;
}
I have made the following changes.
returning false always.
If not invalid calling the addPatron() function
Added event.preventDefault() for additional event bubbling to stop.

Add another function to current JavaScript code?

Can someone please tell me how to add my below JavaScript (function validateEmail() to the JavaScript I already created (function validateForm()? I need to combine the 2 into one. What I did was create a JavaScript to create error messages, then my new one creates an error message if the Email field was typed incorrectly. The longer JavaScript is what needs the shorter one. Do I just add an else if, if than? I am new to JavaScript. Thank you for those that help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
if (email == "") {
emailError.innerHTML = "Please enter your Email";
ret = false;
}
else {
emailError.innerHTML = "";
}
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
NEW JAVASCRIPT
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
return valid;
}
Your final function should look like below:
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
ret &= validateEmail();
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
// in diff file
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
else {
emailError.innerHTML = "";
}
return valid;
}
EDIT
If you can not (or dont want to) change validateForm function to include call to validateEmail then you can specify both functions in the form onsubmit
onsubmit="return validateForm() && validateEmail()"
Your form validation script simply needs to call your additional function as an additional test.
Try adding this to the end of your main function:
if(!validateEmail()) {
// error code
ret=false;
}
else {
// ok
}
return ret;

Javascript email format not validating correctly

The code below validating correctly with exception to the email address field. Do you have any suggestions as to how I can modify the code to get the email address field validation working? I want to ensure real email addresses are being entered and accepted.
$('#topError').empty();
$('#fnameError').empty();
$('#lnameError').empty();
$('#genderError').empty();
$('#bdayError').empty();
$('#emailError').empty();
$('#pass1Error').empty();
$('#pass2Error').empty();
$('#passcError').empty();
var fname = Apperyio('register_firstname').val();
var lname = Apperyio('register_lastname').val();
var gender = Apperyio('register_gender').val();
var bmonth = Apperyio('register_birthdaymonth').val();
var bday = Apperyio('register_birthdayday').val();
var byear = Apperyio('register_birthdayyear').val();
var email = Apperyio('register_email').val();
var pass1 = Apperyio('register_password1').val();
var pass2 = Apperyio('register_password2').val();
var re = /^(([^<>()[]\.,;: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,}))$/igm;
var errorMsg = "";
if ($.trim(fname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("fnameError").innerHTML = "Please enter your first name.";
}
if ($.trim(lname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("lnameError").innerHTML = "Please enter your last name.";
}
if ($.trim(gender) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("genderError").innerHTML = "Please select your gender.";
}
if ($.trim(bmonth) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(bday) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(byear) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
if ($.trim(email) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter your email address.";
}
if (email.val() === "" || !re.test(email.val()))
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter a vaild email address.";
}
if ($.trim(pass1.length) < 6)
{
errorMsg = errorMsg + "1";
document.getElementById("pass1Error").innerHTML = "Please enter a password of at least 6 characters.";
}
if ($.trim(pass2) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("passcError").innerHTML = "Please confirm your password.";
}
if ($.trim(pass1) !== $.trim(pass2))
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "The passwords you entered do not match.";
}
if (errorMsg === "")
{
//signupService.execute({});
Apperyio.User.createUser({
"username": Apperyio('register_email').val(),
"password": Apperyio('register_password1').val(),
"email": Apperyio('register_email').val(),
"firstName": Apperyio('register_firstname').val(),
"lastName": Apperyio('register_lastname').val(),
"gender": Apperyio('register_gender').val(),
"birthday": (Apperyio('register_birthdayyear').val() + Apperyio('register_birthdaymonth').val() + Apperyio('register_birthdayday').val())
})
.then(function(result){
Apperyio.navigateTo('Position1');
}
);
}
Update: I was able to resolve the issue. Thank you for your help.
Here is the updated code:
$('#topError').empty();
$('#fnameError').empty();
$('#lnameError').empty();
$('#genderError').empty();
$('#bdayError').empty();
$('#emailError').empty();
$('#pass1Error').empty();
$('#pass2Error').empty();
$('#passcError').empty();
var fname = Apperyio('register_firstname').val();
var lname = Apperyio('register_lastname').val();
var gender = Apperyio('register_gender').val();
var bmonth = Apperyio('register_birthdaymonth').val();
var bday = Apperyio('register_birthdayday').val();
var byear = Apperyio('register_birthdayyear').val();
var email = Apperyio('register_email').val();
var pass1 = Apperyio('register_password1').val();
var pass2 = Apperyio('register_password2').val();
var dateString = (bmonth + "/" + bday + "/" + byear);
var errorMsg = "";
if ($.trim(fname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("fnameError").innerHTML = "Please enter your first name.";
}
if ($.trim(lname) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("lnameError").innerHTML = "Please enter your last name.";
}
if ($.trim(gender) === "")
{
errorMsg = errorMsg + "1";
document.getElementById("genderError").innerHTML = "Please select your gender.";
}
var date_regex = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2})$/;
if (!(date_regex.test(dateString)))
{
errorMsg = errorMsg + "1";
document.getElementById("bdayError").innerHTML = "Please enter your birthday.";
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
if ($.trim(email).length === 0) {
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter a valid email address.";
// e.preventDefault();
}
if (validateEmail(email)) {
//alert('Email is valid');
}
else {
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "Please enter a valid email address.";
// e.preventDefault();
}
if ($.trim(pass1.length) < 6)
{
errorMsg = errorMsg + "1";
document.getElementById("pass1Error").innerHTML = "Please enter a password of at least 6 characters.";
}
if ($.trim(pass2) === "" & $.trim(pass1) !== "")
{
errorMsg = errorMsg + "1";
document.getElementById("passcError").innerHTML = "Please confirm your password.";
}
if ($.trim(pass1) !== $.trim(pass2))
{
errorMsg = errorMsg + "1";
document.getElementById("emailError").innerHTML = "The passwords you entered do not match.";
}
if (errorMsg === "")
{
//signupService.execute({});
Apperyio.User.createUser({
"username": Apperyio('register_email').val(),
"password": Apperyio('register_password1').val(),
"email": Apperyio('register_email').val(),
"firstName": Apperyio('register_firstname').val(),
"lastName": Apperyio('register_lastname').val(),
"gender": Apperyio('register_gender').val(),
"birthday": (Apperyio('register_birthdayyear').val() + Apperyio('register_birthdaymonth').val() + Apperyio('register_birthdayday').val())
})
.then(function(result){
Apperyio.navigateTo('Position1');
}
);
}

.update Not working -- Meteor

For some odd reason, my .update function isn't properly functioning. I thought the selector of this._id is the issue here, but I tried passing in a raw ID of one of the items in my database instead. With good_input, the .insert content is all stored in the database but the .update is merely skipped looking at the results.
Template.newInstitution.events({
'click #form_institution': function () {
var inst_name = $('#name')[0].value;
var inst_type = $('#type')[0].value;
var inst_school = $('#school')[0].value;
var inst_desc = $('#description')[0].value;
var good_input = true;
if (inst_name === "") {
$('#name')[0].placeholder = "Please enter a name";
$('#nameDiv').addClass("has-error");
good_input = false;
}
if (inst_type === "") {
$('#type')[0].placeholder = "Please enter a type";
$('#typeDiv').addClass("has-error");
good_input = false;
}
if (inst_school === "") {
$('#school')[0].placeholder = "Please enter your affiliated school";
$('#schoolDiv').addClass("has-error");
good_input = false;
}
if (inst_desc === "") {
$('#description')[0].placeholder = "Please enter a description";
$('#descDiv').addClass("has-error");
good_input = false;
}
if (good_input) {
Institutions.insert({
admin: Meteor.userId(),
title: inst_name,
type: inst_type,
school: inst_school,
description: inst_desc
});
Institutions.update({_id: this._id},
{$push: {
members: Meteor.userId()
}}
);
Router.go('songs');
}
}
});
https://bpaste.net/show/befaba419c19
Would someone identify the issue here and explain the cause of it?
Where do you think that this._id is being set? Unless there is some further context not visible, there's no such thing. While I agree that you should just include the data in the initial insert, probably what you're looking for is var id = Institutions.insert({...}) and using id instead of this._id.
This was the fix. Basically, I can just set an array in the original statement and use $push later.
Template.newInstitution.events({
'click #form_institution': function () {
var inst_name = $('#name')[0].value;
var inst_type = $('#type')[0].value;
var inst_school = $('#school')[0].value;
var inst_desc = $('#description')[0].value;
var good_input = true;
if (inst_name === "") {
$('#name')[0].placeholder = "Please enter a name";
$('#nameDiv').addClass("has-error");
good_input = false;
}
if (inst_type === "") {
$('#type')[0].placeholder = "Please enter a type";
$('#typeDiv').addClass("has-error");
good_input = false;
}
if (inst_school === "") {
$('#school')[0].placeholder = "Please enter your affiliated school";
$('#schoolDiv').addClass("has-error");
good_input = false;
}
if (inst_desc === "") {
$('#description')[0].placeholder = "Please enter a description";
$('#descDiv').addClass("has-error");
good_input = false;
}
if (good_input) {
Institutions.insert({
admin: Meteor.userId(),
title: inst_name,
type: inst_type,
school: inst_school,
description: inst_desc,
members: [Meteor.userId()]
});
Router.go('songs');
}
}
});

Form doesn't return true and won't send to PHP

So the validation for the form works, but I cannot get it to send to the php file. I'm assuming it has something to do with the return false/true and the end.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '')
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
if (email == '')
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
if (msg == '')
{
$('.msgerror').html('What can we help you with?').fadeIn(1000);
}
return false;
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
I think your last section of code should read like this:
if($.trim($('.nameerror').text()) == '')
{
// You can do stuff here first if everything is good.
return true;
}
else
{
// Or you can do stuff here for a failed submission.
return false;
}
You are exiting the function before the last if statement is checked.
You must use this code:
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
if (name == '') {
{
$('.nameerror').html('Please provide your name').fadeIn(1000);
}else if
(!validateName(name)) {
$('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000);
}
return false;
}
if (email == '') {
{
$('.emailerror').html('Please provide your email').fadeIn(1000);
}else if
(!validateEmail(email)) {
$('.emailerror').html('Invalid email format').fadeIn(1000);
}
return false;
}
if (msg == '') {
$('.msgerror').html('What can we help you with?').fadeIn(1000);
return false;
}
if($.trim($('.nameerror').text()) == ''){
return true;
}
};
Instead of checking to see if a particular element has html in it... why don't you just set a flag? This makes everything a bit more simplistic.
function validateForm(contact) {
var name = document.getElementById('name').value
var email = document.getElementById('email').value
var msg = document.getElementById('message').value
var flag = true;
//do this for each of your if statements
if(there is an error case) {
//do whatever you want to the DOM
flag = false;
}
return flag;
}

Categories