只有当它返回true时才可以在if语句中调用函数

时间:2013-10-03 22:54:48

标签: javascript

我试图在if语句中调用函数,只有它返回true。下面的函数检查用户名字段,以确保其中有东西,如果它将它发送到函数验证表单

function usernamecheck() {
    if ($("#signupUsername").val().length < 4) {

        return true;
    }
}

function validateForm() {

    if (usernamecheck(returns true)) {
        //run code
    }
}

是否可能/最佳方式

1 个答案:

答案 0 :(得分:2)

function usernamecheck() {
    //Updated this to just return the expression.  It will return true or false.
    return $("#signupUsername").val().length < 4;        
}

function validateForm() {
    //Here we just call the above function that will either return true or false.
    //So by nature the if only executes if usernamecheck() returns true.
    if (usernamecheck()) {
        //Success..Username passed.
    }
}