-2

I am working on a project that uses a text editor to generate styles content behind the scenes and updates the value of an hidden input with the html contents.

A component has been developed for a specific version of this text editor with a focus on uploading a single image only. When uploading a single image as needed, the input value will be structured as follows:

<input id='image' type='hidden' value='<p><img src="some url"></p>' />

I'd like to generate some regex that will grab the hidden input value and validate for this <p><img src='...'/></p> structure and disqualify any other structure. i.e. multiple images from being uploaded into the editor, any text surrounding the image after upload, text only without any image, etc.

Is this possible to achieve with regex? something like:

methods: {
        isValidImage(inputValue) {
            //validate with regex
            return isValid;
        }
    }

Thanks in advance

AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • Why not place the url in the `value`, then when it is valid grab it and place it within the `src`? – Get Off My Lawn Jul 15 '18 at 15:33
  • The special text editor generates the value and encodes it to a long string, also rendering it out within the editor. – AnchovyLegend Jul 15 '18 at 15:38
  • @AnchovyLegend maybe you can rephrase your question and tag it as xpath to fix it. – wp78de Jul 16 '18 at 16:07
  • While the Anti-Cthulhu regex rant is humorous it is [not a good answer](https://meta.stackoverflow.com/questions/261561/please-stop-linking-to-the-zalgo-anti-cthulhu-regex-rant) and [some think](https://meta.stackoverflow.com/questions/261561/please-stop-linking-to-the-zalgo-anti-cthulhu-regex-rant#comment48072_261561) links to it are used in an unhelpful slapdown manner. – wp78de Jul 23 '18 at 16:09

1 Answers1

2

I would actually solve this problem using XPath in JavaScript. Load the string to a DOMParser and query the value of a src attribute of img beneath p:

function isValidImgSrc(inputValue) {
  var doc = new DOMParser().parseFromString(inputValue,'text/xml');
  var result = doc.evaluate('//p/img/@src', doc, null, XPathResult.STRING_TYPE, null);
  console.log(result.stringValue);
  if (result && result.stringValue && result.stringValue !== "" ) {
      //maybe you want to do further checks to test if the url is actually valid...
      return true;
  }
  return false;
}

let input = `<p><img src='test'/></p>`;
console.log(isValidImgSrc(input));
wp78de
  • 18,207
  • 7
  • 43
  • 71