简体   繁体   English

如何在归档验证中使用 JavaScript Switch Case

[英]How To Use JavaScript Switch Case in Filed Validation

I am trying a simple input validation at This Demo and as you can see I am using some nested if statements (which can be more for applying more validation rules).我正在这个演示中尝试一个简单的输入验证,正如你所看到的,我使用了一些嵌套的 if 语句(这可以更多地用于应用更多的验证规则)。 Now my question is if you can help me to use JavaScript Switch Statement instead of theses if statement the reason which I got confused is the (expression) and default: part of the statement which I am totally confused how to use them in my case?现在我的问题是,如果您能帮助我使用 JavaScript Switch 语句而不是这些 if 语句,我感到困惑的原因是(expression)default:语句的一部分,我完全困惑如何在我的情况下使用它们?

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}

and here is my code:这是我的代码:

$(function () {
    $("#pro").on("click", function (e) {
        inputData = $.trim($('input[type="text"]').val());
        if (inputData == ""){
            alert("Field Can not be Empty");
        }
        else if (inputData.length<3){
            alert("Field Can Be Less Than 4");
        }
        else
        {
         alert($('input[type="text"]').val());
        }
        e.preventDefault();
    });
});

Thanks谢谢

That's not the way, how switch statement works.这不是方法,switch 语句是如何工作的。 You can not write different expressions in the case of a switch.在 switch 的情况下,您不能编写不同的表达式。 It can only compare the expression to a single value defined in a case statement.它只能将表达式与 case 语句中定义的单个值进行比较。 See another explanation at: Expression inside switch case statement请参阅以下位置的另一种解释: switch case 语句中的表达式

An example of how to use switch() statement would be like this:如何使用switch()语句的示例如下:

var expression = "1";

switch(expression) {
    case "1":
        //this will be executed
        break;
    case "2":
        //wont be executed
        break;
    default:
        //wont be executed, since a match was found
}

It is better to use one switch instead of using 2-3 if/then/else statements.最好使用一个switch而不是使用 2-3 个if/then/else语句。

You can find more examples here: http://www.w3schools.com/js/js_switch.asp您可以在此处找到更多示例: http : //www.w3schools.com/js/js_switch.asp

Although not a good way to use switches you ca proceed like this:虽然不是使用开关的好方法,但您可以这样进行:

switch(true){
 case (inputData == "") :
 // your code
 break;
 case (inputData.length<3) :
 //your code
 break;
 default:
 //your code
 break;
}

If else statement is suit here. If else语句适合这里。 It is difficult to use switch here.在这里很难使用switch Let us look the switch让我们看看switch

$(function () {
    $("#pro").on("click", function (e) {
        inputData = $.trim($('input[type="text"]').val());

        var len = inputData.length;
        switch(len)
        {
            case 0:
                alert("Field Can not be Empty");
                break;
            case 1:
                alert("Field Can't Be Less Than 4");
                break;
             case 2:
                alert("Field Can't Be Less Than 4");
                break;
             case 3:
                alert("Field Can't Be Less Than 4");
                break;
            default:
                alert($('input[type="text"]').val());
        }
        e.preventDefault();
    });
});

The code looks lengthy and become make problem for more condition.代码看起来很长,并成为更多条件的问题。 So the if else is the better solution here.所以if else是这里更好的解决方案。

switch demo切换演示

You can write expressions in case clauses but you have to return the value for comparison.您可以在 case 子句中编写表达式,但必须返回值进行比较。

 $(function () { var $input = $('input[type="text"]'); $('button').on('click', validateInput) function validateInput(e) { e.preventDefault(); var alertMsg = ""; var inputData = $.trim($input.val()); switch(inputData) { case "": alertMsg = "Field Can not be Empty"; break; case (inputData.length < 4 && inputData): alertMsg = "Field Can't Be Less Than 4"; break; default: alertMsg = inputData; } alert(alertMsg); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"><button>Click here</button>

In my case I used switch as an exercise to a form in Bootstrap.就我而言,我使用 switch 作为 Bootstrap 表单的练习。 Due so I let the break between the cases as the program keeps tracking for more fields, so it doesn't need to check every variant on it and jumps to the next field.由于程序不断跟踪更多字段,因此我在案例之间进行了中断,因此它不需要检查其上的每个变体并跳转到下一个字段。 I made and object with the conditions that the switch should look for.我提出并反对开关应该寻找的条件。 Pls, do remember that this is a schoolar exercise and my boundaries were quite clear: no if/else allowed.请记住,这是一个学校练习,我的界限很明确:不允许 if/else。 Here is the code这是代码

//taking input value field
 let mailLine = inputEmail.value;

//obj mail
let mailObj = {

    case1 : (mailLine == ""),
    case2 : (!checkValidity(mailLine)), 
   //function check, no need to place it here!

}
//if the cases are true
switch (true) {

    case mailObj.case1:
          
    inputEmail.classList.add("is-invalid");//bootstrap div
    
    document.getElementById("errorEmail").textContent = "No empty field allowed";
    
    counter ++; //for more stuff in the code
        
        break; //left it on purpose. No itineration. So it goes to password, city...

    case mailObj.case2:
   
    inputEmail.classList.add("is-invalid");
    
    document.getElementById("errorEmail").textContent = "Not right mail format";
   
    counter ++;
        
        break;

    default:
    
    inputEmail.classList.remove("is-invalid");
    
    inputEmail.classList.add("is-valid");
    
    document.getElementById("okEmail").textContent = "Right mail format";
    
        break;
}

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

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