简体   繁体   English

如何将两个if语句合并为一个?

[英]How to combine two if statements into one?

I know there is a much cleanlier way to write this than multiple if statements but when I try to combine them my validation stops working! 我知道有一种比使用多个if语句更干净的方法,但是当我尝试将它们组合时,我的验证就会停止工作! This isn't good practice right? 这不是好习惯吧? Or in this case is two different if statements okay? 还是在这种情况下,两个不同的if语句可以吗?

My code: 我的代码:

function validateForm() {
    var success = true;
    var x = document.forms["contestForm"]["firstName"].value;

    if (x == null || x == "") {

        addClass($('#firstNamespan'), 'formError');
        removeClass($('.validationError'), 'is-hidden');
        success = false;
    } else {
        removeClass($('#firstNamespan'), 'formError');
        addClass($('.validationError'), 'is-hidden');
    }

    var x = document.forms["contestForm"]["lastName"].value;

    if (x == null || x == "") {
        addClass($('#lastNamespan'), 'formError');
        removeClass($('.validationError'), 'is-hidden');
        success = false;
    } else {
        removeClass($('#lastNamespan'), 'formError');        
    }
    return success;
}

My attempt to combine: 我的尝试结合:

function validateForm() {
    var success = true;
    var x = document.forms["contestForm"]["firstName", "lastName"].value;

    if (x == null || x == "") {
        addClass($('#firstNamespan', '#lastNamespan'), 'formError');
        removeClass($('.validationError'), 'is-hidden');
        success = false;
    } else {
        removeClass($('#firstNamespan', '#lastNamespan'), 'formError');
    }
    return success;
}

So what am I doing wrong? 那我在做什么错? I also will need to add a birthday and e-mail validation but I wanted to get this cleaned up first before it became a monster of if else statements! 我还需要添加生日和电子邮件验证,但我想先清理一下它,使其成为if else语句的怪兽! Sorry for the extra non-helpful information its making me write more because I have to much code. 对不起,因为这些额外的无用信息使我不得不编写更多代码,因为我需要编写大量代码。 Please feel free to edit and delete this once its posted. 发布后,请随时对其进行编辑和删除。

Combine them by functional programming: 通过功能编程将它们组合:

function validateForm() {
    var x = document.forms["contestForm"]["firstName"].value;
    //calls the function checkObject with the object x and the id
    var success1 = checkObject(x, '#firstNamespan');
    //the result of success1 is either true or false.

    var x = document.forms["contestForm"]["lastName"].value;
    //calls the function checkObject with the object x and the id
    var success2 = checkObject(x, '#lastNamespan');
    //the result of success2 is either true or false.

    //returns true if both success1 and success2 are true, otherwise returns false.
    return success1 && success2;
}

function checkObject(x, id)
{
    if (x == null || x == "") {
        addClass($(id), 'formError');
        removeClass($('.validationError'), 'is-hidden');
        return false;
    } else {
        removeClass($(id), 'formError');        
        return true;
    }
}

Which could then be condensed into 然后可以将其浓缩为

function validateForm() {
    return checkObject($('form[name="frmSave"] #firstName').val(), '#firstNamespan') && checkObject($('form[name="frmSave"] #lastName').val(), '#lastNamespan');
}

function checkObject(x, id)
{
    if (x == null || x == "") {
        addClass($(id), 'formError');
        removeClass($('.validationError'), 'is-hidden');
        return false;
    } else {
        removeClass($(id), 'formError');        
        return true;
    }
}

Answer for N number of fields with your pattern of naming 用您的命名模式回答N个字段

function validateForm() {
    var itemsToValidate = ["#firstName", "#lastName", "#birthday", "#email"];
    var results = [];
    $.map( itemsToValidate, function( val, i ) {
        results.push(checkObject($('form[name="frmSave"] ' + val).val(), val + 'span'));
    });

    for(var i=0; i<results.length; i++)
    {
        if(results[i] == false)
            return false;
    }
    return true;
}

function checkObject(x, id)
{
    if (x == null || x == "") {
        addClass($(id), 'formError');
        removeClass($('.validationError'), 'is-hidden');
        return false;
    } else {
        removeClass($(id), 'formError');        
        return true;
    }
}

Note: I didn't validate any of the JavaScript above please call me out if i made a mistake. 注意:我没有验证上面的任何JavaScript,如果我出错了,请给我打电话。 I just typed this up in notepad as i'm out the door at work 我刚在工作时在记事本中输入

Break things up into functions and utilize an array to loop through the fields to validate. 将其分解为功能,并利用数组循环遍历字段以进行验证。

function isValidField(fieldName) {
    var value = document.forms["contestForm"][fieldName].value;
    return !(value == null || value == "");
}

function displayFieldError(fieldName) {
    addClass($('#' + fieldName + 'span'), 'formError');
    removeClass($('.validationError'), 'is-hidden');
}

var fields = ['firstName', 'lastName'];
var isValidForm = true;

fields.map(function(fieldName) {
    if (!isValidField(fieldName)) {
        displayFieldError(fieldName);
        isValidForm = false;
    }
});

if (isValidForm) {
    // Form is correct, do something.
}

By giving them a seperate identifier like this 通过给他们一个单独的标识符,像这样

var x = document.forms["contestForm"]["firstName"].value;
var y = document.forms["contestForm"]["lastName"].value;

if ((x == null || x == "") && (y == null || y == "")) {

    addClass($('#firstNamespan'), 'formError');
    removeClass($('.validationError'), 'is-hidden');

    addClass($('#lastNamespan'), 'formError');
    removeClass($('.validationError'), 'is-hidden');
    success = false;

} else {
    removeClass($('#firstNamespan'), 'formError');
    addClass($('.validationError'), 'is-hidden');

    removeClass($('#lastNamespan'), 'formError');        
}

But you need to be more precise about, what would you do with just addClass ? 但是您需要更加精确,仅使用addClass会做什么? That won't work. 那行不通。 You need have a JS object before this method call. 在此方法调用之前,您需要一个JS对象。

I think, you want some element there before the addClass and removeClass . 我认为,您需要在addClassremoveClass之前的某个元素。 Or they need to be like this 或者他们需要像这样

$('#firstNamespan').removeClass('formError');

Like this, you need to change your code. 这样,您需要更改代码。 So that the object comes first and then the method call. 这样对象首先出现,然后是方法调用。

Make it a function, 发挥作用,

function validateForm(formName) {
  var x =  document.forms["contestForm"][formName].value;
  if (x == null || x == "") {
    addClass($('#' + formName + 'span'), 'formError');
    removeClass($('.validationError'), 'is-hidden');
    return false;
  }
  removeClass($('#' + formName + 'span'), 'formError');
  addClass($('.validationError'), 'is-hidden');
  return true;
}

then you can call it twice, 那你可以打两次

function validateForm() {
  var success = validateForm('firstName');
  if (success) {
    success = validateForm('lastName');
  }
  return success;
}

The two ifs are checking two different form elements, and showing and hiding two different validation error elements. 这两个if检查两个不同的表单元素,并显示和隐藏两个不同的验证错误元素。

Combining them will not be just a code refactor but also change functionality. 合并它们不仅是代码重构,而且还会更改功能。

The only thing they have in common are that they both use the same variable 'x'. 它们唯一的共同点是它们都使用相同的变量“ x”。

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

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