Having a main function call smaller functions? - javascript

I've got three separate functions for my javascript:
<script>
function validateName() {
var x = document.forms["booking_form"]["firstname"].value;
if (x == null || x == ""){
alert("First name is not filled");
return false;
}
var y = document.forms["booking_form"]["lastname"].value;
if (y == null || y == ""){
alert("Last name is not filled");
return false;
}
//var z =
}
function validateAge(){
if(document.booking_form.age.value < 18){
alert("You must be at least 18 years of age");
return false;}
else{
return true;}
}
function validateEmail(){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(booking_form.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
</script>
How do I call these separate functions into one main function? I'm not very good with Javascript, so I'm pretty stumped :|

If I understand correctly (let me know if I don't), it looks like you want to create a function that calls each of these individual functions and returns true only if all three validations succeed.
To do that, you'd simply use the && operator like this:
function validate() {
return validateAge() && validateName() && validateEmail();
}
This function will tell you if the age is valid AND the name is valid AND the email is valid.
For this to work, as nnnnnn pointed out, you'd have to return true in the last line of your validateName function; otherwise it would return undefined when the validation succeeds.

Just make a new function and this call others
<script>
function validateName() {
var x = document.forms["booking_form"]["firstname"].value;
if (x == null || x == ""){
alert("First name is not filled");
return false;
}
var y = document.forms["booking_form"]["lastname"].value;
if (y == null || y == ""){
alert("Last name is not filled");
return false;
}
//var z =
}
function validateAge(){
if(document.booking_form.age.value < 18){
alert("You must be at least 18 years of age");
return false;}
else{
return true;}
}
function validateEmail(){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(booking_form.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
function globalFunction() {
validateAge();
validateName();
validateEmail();
}
</script>
In this example, you need call a "globalFunction();"
Bye

Related

exporting function return value

I have a code below
function createRoom(){
$(document).keyup(function(event) {
if ($("#room_name").is(":focus") && event.key == "Enter") {
var plainText = document.querySelector(".create-room-class").value;
var createRoomName = plainText.replace(/(<([^>]+)>)/gi, "");
createRoomName = createRoomName.replace(/ +/g, "");
createRoomName = createRoomName.trim();
if(createRoomName.length == 0){
alert("empty");
} else if(createRoomName.length < 5){
alert("Room name must be equal or longer than 5 characters");
} else if(!createRoomName.length == 0)
{
getCreatedRoomName(createRoomName);
window.location = createRoomName;
}
}
});
}
createRoom();
function getCreatedRoomName(x){
return x;
}
What it does is first checks if input field is not empty and if not smaller than 5 characters. If everything is fine then we pass that value to a function and then redirect to that created name url. Look below.
getCreatedRoomName(createRoomName);
window.location = createRoomName;
And we return value (return x)
function getCreatedRoomName(x){
return x;
}
How can I retrieve that returned value in nodejs? I tried modules it doesn't work for some reason.

Javascript Validation not working (onSubmit)

Vaidation function called on submit.
HTML
<input type="submit" class="submit" value="submit">
JS
window.load = function() {
var form = document.getElementById('form');
form.onsubmit = function(e) {
return validate(); // will be false if the form is invalid
}
}
Validate()
function validate() {
var x = document.forms["form"]["fname"].value;
var y = document.forms["form"]["pname"].value;
var email = document.forms["form"]["email"].value;
var phone = document.forms["form"]["phone"].value;
var date = document.forms["form"]["date"].value;
var month = document.forms["form"]["month"].value;
var year = document.forms["form"]["year"].value;
return false;
alert('wass');
if (x==null || x == "" || isNaN(x) == false) {
alert("Check Name, It can't have numbers. You can use Roman numbers.");
return false;}
else if (y == null || y == "") {
alert("Picture Name must be filled out");
return false;
}
else if(email == '' || email.indexOf('#') == -1 || email.indexOf('.') == -1)
{
alert("Insert valid Email Address");
return false;
}
else if(phone == ''|| phone <1000000000 || phone >9999999999){
alert("Enter valid phone number");
return false;
}else if(date =='' || date<01 || date >31){
alert("Enter valid Date ");
return false;
}else if(month =='' || month<1 || month >12){
alert("Enter valid Month ");
return false;
}else if(year =='' || year<1800 || year >2016){
alert("Enter valid Year ");
return false;
}
//Function used to make colors red instead of individual codelines
function makeRed(inputDiv){
inputDiv.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.color="#FFFFFF";
}
//Function made to clean the divs when the validation is met.
function makeClean(inputDiv){
inputDiv.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.color="#000000";
}
}
Form still gets submitted. Possible issues?
You'll need to prevent the default form submission using:
e.preventDefault();
Place this above your validate function.
Then use the submit() function on the form to actually submit the form provided your validation passes.
At the minute your form is submitting regardless.
You need to prevent default functionality of form submit, by calling e.preventDefault(). In your case:
window.load = function () {
document.getElementById('form').onsubmit = function (e) {
if (!validate()) {
e.preventDefault();
}
}
}

How to combine two if statements into one?

I know there is a much cleanlier way to write this than multiple if statements but when I try to combine them my validation stops working! This isn't good practice right? Or in this case is two different if statements okay?
My code:
function validateForm() {
var success = true;
var x = document.forms["contestForm"]["firstName"].value;
if (x == null || x == "") {
addClass($('#firstNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan'), 'formError');
addClass($('.validationError'), 'is-hidden');
}
var x = document.forms["contestForm"]["lastName"].value;
if (x == null || x == "") {
addClass($('#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#lastNamespan'), 'formError');
}
return success;
}
My attempt to combine:
function validateForm() {
var success = true;
var x = document.forms["contestForm"]["firstName", "lastName"].value;
if (x == null || x == "") {
addClass($('#firstNamespan', '#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan', '#lastNamespan'), 'formError');
}
return success;
}
So what am I doing wrong? I also will need to add a birthday and e-mail validation but I wanted to get this cleaned up first before it became a monster of if else statements! Sorry for the extra non-helpful information its making me write more because I have to much code. Please feel free to edit and delete this once its posted.
Combine them by functional programming:
function validateForm() {
var x = document.forms["contestForm"]["firstName"].value;
//calls the function checkObject with the object x and the id
var success1 = checkObject(x, '#firstNamespan');
//the result of success1 is either true or false.
var x = document.forms["contestForm"]["lastName"].value;
//calls the function checkObject with the object x and the id
var success2 = checkObject(x, '#lastNamespan');
//the result of success2 is either true or false.
//returns true if both success1 and success2 are true, otherwise returns false.
return success1 && success2;
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Which could then be condensed into
function validateForm() {
return checkObject($('form[name="frmSave"] #firstName').val(), '#firstNamespan') && checkObject($('form[name="frmSave"] #lastName').val(), '#lastNamespan');
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Answer for N number of fields with your pattern of naming
function validateForm() {
var itemsToValidate = ["#firstName", "#lastName", "#birthday", "#email"];
var results = [];
$.map( itemsToValidate, function( val, i ) {
results.push(checkObject($('form[name="frmSave"] ' + val).val(), val + 'span'));
});
for(var i=0; i<results.length; i++)
{
if(results[i] == false)
return false;
}
return true;
}
function checkObject(x, id)
{
if (x == null || x == "") {
addClass($(id), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
} else {
removeClass($(id), 'formError');
return true;
}
}
Note: I didn't validate any of the JavaScript above please call me out if i made a mistake. I just typed this up in notepad as i'm out the door at work
Break things up into functions and utilize an array to loop through the fields to validate.
function isValidField(fieldName) {
var value = document.forms["contestForm"][fieldName].value;
return !(value == null || value == "");
}
function displayFieldError(fieldName) {
addClass($('#' + fieldName + 'span'), 'formError');
removeClass($('.validationError'), 'is-hidden');
}
var fields = ['firstName', 'lastName'];
var isValidForm = true;
fields.map(function(fieldName) {
if (!isValidField(fieldName)) {
displayFieldError(fieldName);
isValidForm = false;
}
});
if (isValidForm) {
// Form is correct, do something.
}
By giving them a seperate identifier like this
var x = document.forms["contestForm"]["firstName"].value;
var y = document.forms["contestForm"]["lastName"].value;
if ((x == null || x == "") && (y == null || y == "")) {
addClass($('#firstNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
addClass($('#lastNamespan'), 'formError');
removeClass($('.validationError'), 'is-hidden');
success = false;
} else {
removeClass($('#firstNamespan'), 'formError');
addClass($('.validationError'), 'is-hidden');
removeClass($('#lastNamespan'), 'formError');
}
But you need to be more precise about, what would you do with just addClass? That won't work. You need have a JS object before this method call.
I think, you want some element there before the addClass and removeClass. Or they need to be like this
$('#firstNamespan').removeClass('formError');
Like this, you need to change your code. So that the object comes first and then the method call.
Make it a function,
function validateForm(formName) {
var x = document.forms["contestForm"][formName].value;
if (x == null || x == "") {
addClass($('#' + formName + 'span'), 'formError');
removeClass($('.validationError'), 'is-hidden');
return false;
}
removeClass($('#' + formName + 'span'), 'formError');
addClass($('.validationError'), 'is-hidden');
return true;
}
then you can call it twice,
function validateForm() {
var success = validateForm('firstName');
if (success) {
success = validateForm('lastName');
}
return success;
}
The two ifs are checking two different form elements, and showing and hiding two different validation error elements.
Combining them will not be just a code refactor but also change functionality.
The only thing they have in common are that they both use the same variable 'x'.

Validating using JavaScript - how to show to all validation error message's

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:
function validateForm()
{
var sName=document.forms["myForm"]["surname_5"].value;
if (sName==null || sName=="")
{
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
return false;
}
var x=document.forms["myForm"]["firstname_4"].value;
if (x==null || x=="")
{
document.getElementById("fNameMessage").innerHTML = "*First name is required";
return false;
}
var y=document.forms["myForm"]["selectid"];
if(y.options[y.selectedIndex].value == "Title")
{
document.getElementById("titleMessage").innerHTML = "You need to select a title";
return false;
}
}
How do I get it so all validation messages show if the user has left all fields blank?
Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.
Try something like this (or add all your code if you need more details)
JavaScript:
function validateForm() {
var sName = document.forms["myForm"]["surname_5"].value;
var ret = true;
if (sName == null || sName == "") {
document.getElementById("sNameMessage").innerHTML = "*Surname is required";
ret = false;
}
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "*First name is required";
ret = false;
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
ret = false;
}
return ret;
}

Combining 2 IF/ELSE statements (validation)

I am trying to combine 2 IF/Else statements to create one validation function. This is my code for the 2 separate validations:
function validateCarsMin(v){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
return '1B cannot contain a value if CW is entered';
}
} else return true
}
function validateRateLoc3(v){
if (v != ''){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
return 'This Value is not valid';
}}
}
I did not know if there was a best practice for this and it so, what would it be?
Thanks for the help on the last question I had.
Change the functions to return either true or false. You can push the msgs to an array to be used later.
var errorMsgs = [];
function validateCarsMin(){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
errorMsgs.push('1B cannot contain a value if CW is entered');
return false;
}
} else{
return true;
}
}
function validateRateLoc3(){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
errorMsgs.push('This Value is not valid');
return false;
}};
}
function validateForm(){
var isValid = false;
isValid = validateCarsMin();
isValid = (!isValid) ? isValid:validateRateLoc3();
return isValid;
}
Note I removed the v parameter because it seemed irrelevant. It is not used in the first function and it creates a syntax error in the second.

Categories

Resources