检查字符串是否为null或未定义总是返回False

时间:2020-04-10 15:46:19

标签: typescript angular8

我使用以下代码检查字符串是否为空或已定义。但是即使字符串具有值,它也会返回false。

  filename: string;

  validate(): boolean {
        if (this.filename) {
            this.error = true;
            this.message = "Please enter valid filename";
            return false
        }
        }

更新

这就是我绑定值的方式

<input name="filename" id="filename" pr_ngcontent-oci-c5="" aria-label="filename" class="form-control" placeholder="File Name" type="text" [(ngModel)]="filename">

但是有时,当文件名输入为空时,断点永远不会被击中。有时代码似乎按预期工作。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

编辑:

正如Aymen TAGHLISSIA在评论中所提到的,FormControl可能是实现表单及其验证的一种更为优雅的方法。这是Introduction to forms in Angular,也是使用 Reactive forms 的示例。

原始答案:

使用!this.filename来重写函数:

function validate(): boolean {

  if (!this.filename) {
    this.error = true;
    this.message = "Please enter valid filename";
    return false;
  }

  return true;
}

console.log(validate(null)); // false
console.log(validate(undefined)); // false
console.log(validate('')); // false
console.log(validate('valid')); // true

尽管您也可以考虑将字符串作为参数传递:

function validate(str: string): boolean {

  // Reset error and message?
  // ...      

  if (!str) {
    this.error = true;
    this.message = "Please enter non empty string";
    return false;
  }

  // Or reset error and message here
  // this.error = false;
  // this.message = undefined;

  return true;
}

然后类似:

if (!validate(this.filename)) {
  // Valid filename
} else {
  // Error
}