Does it make sense to check properties separately or together?

Viewed 54

This question stems from a previous question that I asked. How do you access the for loop of the parent component within a child component which has the inputs?

I want to know is it possible to just check for validity from each property separately instead of together? So here is the logic that I have for trying to just check for the title input field and then the url field.

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 ');
    }
  }

The output I am getting is

not valid text

and this is every time I input any text both in the title and url fields. Is there a way for me to check just for the title field? and then use the regex for the url field? Or would I have to split both fields into separate div classes?

Here is the link to the example I am modifying https://stackblitz.com/edit/angular-empty-project-zoy4st?file=app%2Fparent.component.ts

1 Answers

To check for the props separately, all you need to do is add a condition in the update function based on $event.prop. If $event.prop is url, then you validate url, if is title you validate title.

That being said, there is a problem with your current validation. You are checking the value of the existing url object, and not the new value coming in. I have updated it here, it seems to work ok:

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

Related