单独或一起检查属性是否有意义?

时间:2019-01-13 22:05:36

标签: javascript angularjs typescript

这个问题源于我之前提出的问题。 How do you access the for loop of the parent component within a child component which has the inputs?

我想知道是否可以单独而不是一起检查每个属性的有效性? 因此,这是我尝试仅检查标题输入字段然后检查url字段的逻辑。

onUrlUpdate($event) {
    var exp = /\b((http|https):\/\/?)[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/?))/;
    // completely overkill, but just used to demonstrate a point
    var url = this.urls.find(_url => {
      // we can see here that the $event.url is actually the same object as the urls[i] that was
      // passed to the child. We do not lose the reference when it is passed to the child or back
      // up to the parent. 
      return $event.url === _url
    });
    if (url.url.match(exp)) {
      url[$event.prop] = $event.newValue;
     console.log(`Updated URL's "${$event.prop}" property with the value "${$event.newValue}"`);
    }  else if(url.title === ''){
        console.log('not valid text ');
    }
  }

我得到的输出是

  

无效的文字

,这是我每次在title和url字段中都输入任何文本的时候。我有办法只检查标题字段吗?然后将正则表达式用于url字段?还是我必须将两个字段都拆分为单独的div类?

以下是我正在修改的示例的链接https://stackblitz.com/edit/angular-empty-project-zoy4st?file=app%2Fparent.component.ts

1 个答案:

答案 0 :(得分:1)

要单独检查道具,您需要做的就是在基于$event.prop的更新函数中添加一个条件。如果$event.propurl,则验证URL;如果title是URL,则验证标题。

话说回来,您当前的验证存在问题。您正在检查现有url对象的值,而不是输入的新值。我在这里对其进行了更新,看来可以正常工作:

https://stackblitz.com/edit/angular-empty-project-tcdfup?file=app/parent.component.ts