总是返回false | Javascript |对象

时间:2014-10-22 00:47:42

标签: javascript object

我正在开发一个项目,我在其中引用一个对象/函数中的变量。但我总是返回false。我不确定我是否正确地调用它。

这是验证功能:

app.validation = function(){
    'use strict';
    var validCheck = true;

    if((app.process.user.length < 3) || (app.process.user.length > 50)){
        validCheck = false;
        window.alert("The username is not acceptable. Example: username");
    };
    if((app.process.name.length < 3) || (app.process.name.length > 50) || (!app.process.name.indexOf(" ") === -1)){
        validCheck = false;
        window.alert("The name is not acceptable. Example: John Smith");
    };
    if((app.process.email.length < 3) || (app.process.email.length > 100) || (!app.process.email.indexOf("@") === -1)){
        validCheck = false;
        window.alert("The email is not acceptable. Example: john@mail.co.uk");
    };
    if((app.process.passlength < 6) || (app.process.pass.length > 20)){
        validCheck = false;
        window.alert("The password is not acceptable. Example: password");
    };
    if((app.process.age.length < 1) || (app.process.age.length > 2)){
        validCheck = false;
        window.alert("The age is not acceptable. Example: 22");
    };
    return validCheck;
};

这是存储变量的地方:

app.process = function(){
    'use strict';
    var user = document.getElementById("user").value;
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var pass = document.getElementById("pass").value;
    var age = document.getElementById("age").value;

    var test = app.validation();
    console.log(test);
    if(!test){
        window.alert("Try Again.");
    }else{
        app.reset();
        app.members[app.members.length] = new app.Member(user, name, email, pass, age);
        app.printMembers();
    };
};

此代码还有很多内容,但要在此处发布。这些是导致问题的两个功能。

1 个答案:

答案 0 :(得分:1)

您无法访问app.process个变量,因为它们是该函数的私有变量。您需要以某种方式将这些值传递给app.validation以验证它们。

我这样做的方式是

var data = {
    user: document.getElementById("user").value,
    name: document.getElementById("name").value,
    email: document.getElementById("email").value,
    pass: document.getElementById("pass").value,
    age: document.getElementById("age").value
};

var test = app.validation(data);

在验证中

app.validation = function(data) { ...

并替换app.process.field的每个data.field