Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript in multiple files

Tags:

javascript

I have created two JavaScript files. One file is "validators.js" and the other is "UserValidations.js".

Here is the code for validators.js

function isBlankString(value) {
    if (value.replace(/\s/g, "") == "") {
        return true;

    } else {
        return false;
    }
}

In other JavaScript file I have defined function for validating user name like this.

function validateUsername(element) {

    var username = element.value;

    if(value.replace(/\s/g, "") == ""){
        //nothing to validate
        return;
    }else{
        //validation logic
    }

}

Now as it is obvious I should have used isBlankString(value) method to check string length. But I am clueless about how can I use the function defined in other files?

like image 361
vijay.shad Avatar asked Mar 13 '10 17:03

vijay.shad


2 Answers

Make sure that you include your validators.js file first on the page:

<script src="validators.js"></script>

Now you can use the function of that normally:

function validateUsername(element) {

    var username = element.value;

    if(isBlankString(value)){
        //nothing to validate
        return;
    }else{
        //validation logic
    }

}
like image 122
Sarfraz Avatar answered Nov 15 '22 14:11

Sarfraz


The file that provides the function must be included, in your HTML document, before the function is actually used.

Which means that, to be sure, validators.js should be included before UserValidations.js :

<script src="validators.js" type="text/javascript"></script>
<script src="UserValidations.js" type="text/javascript"></script>
like image 30
Pascal MARTIN Avatar answered Nov 15 '22 16:11

Pascal MARTIN