简体   繁体   English

为什么 if 条件语句在 else if(这是错误的)之后终止,尽管在这个 if 条件语句中有另一个 else if?

[英]Why does if conditional statement terminate after else if(which is false)although there is another else if in this if conditional statement?

I have written this code in nodejs:我在nodejs中编写了这段代码:

let letters = /^[A-Za-z]+$/;
let letter2 = /^[a-z_]+$/;


const registerChecker = async(firstName,lastName,username, email, password, password2) =>{
    let errors = [] 
    // Check required fields
    if(!firstName||!lastName||!username|| !email|| !password || !password2){
        errors.push({msg:'Please fill all fields'})
    }else if(!firstName.match(letters)){
        errors.push({msg:'Firstname must contain only Latin lowercase and uppercase letters("a"-"z")("A"-"Z")'})
    }else if(!lastName.match(letters)){
        errors.push({msg:'Lastname must contain only Latin lowercase and uppercase letters("a"-"z")("A"-"Z")'})
    }else if(username){
        if(!username.match(letter2)){
            errors.push({msg:"Username must contain only lowercase Latin letters ('a' - 'z'), numbers, and underscores ('_')"})
        }
    }else if(password.length<6){
        console.log('Less than 6')
        // Password length
        errors.push({msg:'Password must be at least 7 characters'})
    }else if(password2 !== password){
        // Matching Password
        errors.push({msg:'Password do not match'})
    }
    
    
    return errors
}
registerChecker('firstname','lastname','user_me','hello@gmail.com','pass','fs').then(s=>console.log(s)).catch(er=>console.log(er))

When I run this code, it is working till (else if(password.length<6)) perfectly.当我运行此代码时,它一直工作到(else if(password.length<6))完美。 But this (else if(password.length<6)) else if and under it does not work at all.但是 this (else if(password.length<6)) else if 和 under it 根本不起作用。 What should I do in order to write this code properly?我应该怎么做才能正确编写此代码?

The condition, if(username) , will always be true.条件if(username)将始终为真。 If it isn't true, then the first statement would fail and will never reach here.如果它不是真的,那么第一个语句将失败并且永远不会到达这里。 You can omit this and directly write if(password.length<6){} then your issue will be solved.你可以省略这个,直接写if(password.length<6){}那么你的问题就解决了。

For your code, the error will be empty.对于您的代码, error将为空。

Please find the entire pseudo code with correct if else.如果其他,请找到正确的整个伪代码。

if(!firstName||!lastName||!username|| !email|| !password || !password2){
        errors.push({msg:'Please fill all fields'})
    }else if(!firstName.match(letters)){
        errors.push({msg:'Firstname must contain only Latin lowercase and uppercase letters("a"-"z")("A"-"Z")'})
    }else if(!lastName.match(letters)){
        errors.push({msg:'Lastname must contain only Latin lowercase and uppercase letters("a"-"z")("A"-"Z")'})
    }else if(!username.match(letter2)){
        errors.push({msg:"Username must contain only lowercase Latin letters ('a' - 'z'), numbers, and underscores ('_')"})
    }else if(password.length<6){
        console.log('Less than 6')
        // Password length
        errors.push({msg:'Password must be at least 7 characters'})
    }else if(password2 !== password){
        // Matching Password
        errors.push({msg:'Password do not match'})
    }

You might want to remove the if-else statements and make them if statements, If the condition inside if-else evaluates to true, then rest are skipped.您可能希望删除 if-else 语句并使其成为 if 语句,如果 if-else 中的条件评估为真,则跳过 rest。 Also since we are having multiple user inputs to validate here, it would be a good idea to extract them to seperate functions.此外,由于我们在这里要验证多个用户输入,因此最好将它们提取到单独的函数中。

let letters = /^[A-Za-z]+$/;
let letter2 = /^[a-z_]+$/;

const validateName = (names, errors) => {
    Object.keys(names).forEach(key => {
        if (!names[key].match(letters)) {
            errors.push({
                msg: `${key} must contain only Latin lowercase and uppercase letters("a"-"z")("A"-"Z")`
            });
        }
    });
}

const validateUserName = (username, errors) => {
    if (!username.match(letter2)) {
        errors.push({
            msg: 'Username must contain only Latin lowercase and uppercase letters("a"-"z")("A"-"Z")'
        }); 
    }
}

const validatePassword = (password, password2, errors) => {
    if (password.length < 6) {
        errors.push({msg:'Password must be at least 7 characters'});
    } else if (password !== password2) {
        errors.push({msg:'Password do not match'});
    }
}

const registerChecker = (firstName,lastName,username, email, password, password2) => {
    const errors = [];
    // Check required fields
    if (!(firstName && lastName && username && email && password && password2)) {
        errors.push({msg:'Please fill all fields'});
        return;
    }

    validateName({firstName, lastName}, errors);
    validateUserName(username, errors);
    validatePassword(password, password2, errors);
    
    return errors
};

const errors = registerChecker('firstname','lastname','user_me','hello@gmail.com','pass','fs');
console.log(errors); // [{msg: "Password must be at least 7 characters"}] 

Similarly you can add a function to validate email too.同样,您也可以添加 function 来验证 email。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM