exporting function return value - javascript

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.

Related

Double Condition

It will make selection words starting with "p" and ending with "a". Why it didnt work?
function checkWord(word) {
if (word.charAt(0) = 'p' && word.charAt(word.length - 1) = 'a') {
return true;
} else {
return false;
}
= is used for assigning values, not checking them. Use == for checking the values and === for checking value and types. So, your code should be like:
function checkWord(word) {
if (word.charAt(0) === 'p' && word.charAt(word.length - 1) === 'a') {
return true;
} else {
return false;
}
This should do the trick.
You didn't put 2 equals to if you only put 1 equals you are assigning it and if you put 2 equals you're comparing it the. below code should help
/* Check weather the first letter is equals to p and the last letter is equals to a. */
function checkWord(word) {
let firstPAndLastA = false;
if(word != null){
if (word.charAt(0) == 'p' && word.charAt(word.length - 1) == 'a') {
firstPAndLastA = true;
} else {
firstPAndLastA = false;
}
}
return firstPAndLastA;
}
//Calling Function
console.log(checkWord("ppoa"))

Having a main function call smaller functions?

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

How do I change this format to something like 02X-XXXXXXX?

function checkcomplex(whichcontrol) {
var passcheck=true;
var x=0;
if (whichcontrol.value.length==0)
return true;
else if (whichcontrol.value.length!=11)
passcheck=false;
else {
while (passcheck && x<3) {
if (whichcontrol.value.charAt(x) >='0' && whichcontrol.value.charAt(x) <='9')x++;
else
passcheck=false;
}
if (whichcontrol.value.charAt(x)=='-') x++;
else
passcheck=false;
while (passcheck && x<6) {
if (whichcontrol.value.charAt(x) >='0' && whichcontrol.value.charAt(x) <='9')x++;
else
passcheck=false;
}
if (whichcontrol.value.charAt(x)=='-') x++;
else
passcheck=false;
while (passcheck && x<11) {
if (whichcontrol.value.charAt(x) >='0' && whichcontrol.value.charAt(x) <='9')x++;
else
passcheck=false;
}
}
//end else
if (passcheck)
return true;
else
return errorinfield(whichcontrol,"Must be of the form 999-99-9999!");
}
This currently brings up an alert if the number is not in the format of 999-99-9999 and I want to change this to make it bring up and alert if the number is not in the format of 02X-XXXXXXX (X's being numbers)
Can anyone help me with this?
Something like this?
function checkcomplex(whichcontrol) {
// You can make a trim if you like
whichcontrol.value = whichcontrol.value.trim();
// Check length
if(whichcontrol.value.length == 0)
return true;
// Check if value do not match pattern
// Must start with "02" + one digit + "-" + 7 digits and end of string
if(!whichcontrol.value.match(/^02\d-\d\d\d\d\d\d\d$/))
return errorinfield(whichcontrol,"Must be of the form 02X-XXXXXXX!");
// It is valid
return true;
}

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'.

Javascript test() method syntax error?

I'm attempting to convert (what I've found to be) the best email validation function (located here: http://www.linuxjournal.com/article/9585?page=0,3) from php to javascript. Regardless of the fact that "you shouldn't validate with javascript because javascript can be disabled". Obviously I can't leave in the checkdnsrr() portion of the function, but everything else should be doable with javascript.
So far the function works as expected up until this line:else if(/\.\./.test(domain)) {
I know it's pretty useless without context, so the full function is below. What's also weird is that it gives a "pass" to a line with the exact same regex pattern:else if(/\.\./.test(local)) { which is used a few lines before it. Strange.
function validEmail(email) {
var isValid = true;
var atIndex = email.indexOf("#");
var ending = email.length - 1;
if(typeof(atIndex) == "boolean" && !atIndex) {
isValid = false;
}
else {
var domain = email.substr(atIndex+1);
var local = email.substr(0, atIndex);
var localLen = local.length;
var domainLen = domain.length;
if(localLen < 1 || localLen > 64) {
// local part length exceeded
isValid = false;
}
else if(domainLen < 1 || domainLen > 255) {
// domain part length exceeded
isValid = false;
}
else if(local[0] == '.' || local[localLen-1] == '.') {
// local part starts or ends with '.'
isValid = false;
}
else if(/\.\./.test(local)) {
// local part has two consecutive dots
isValid = false;
}
else if(/^[A-Za-z0-9\\-\\.]+$/.test(domain) == false)
// character not valid in domain part
isValid = false;
}
else if(/\.\./.test(domain)) {
// domain part has two consecutive dots
isValid = false;
}
else if(/^(\\\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/.test(local.replace("\\\\",""))) {
// character not valid in local part unless
// local part is quoted
if(/^"(\\\\"|[^"])+"$/.test(local.replace("\\\\",""))) {
isValid = false;
}
}
}
return isValid;
}
You missed a { in the previous if.
Therefore, that else has no if connected to it.

Categories

Resources