使用JavaScript检查HTML内容是否具有当前网站网址

问题描述 投票:0回答:1

我正在使用TinyMCE作为HTML编辑器。我想执行移动和URL验证。

不应被允许:当用户键入除当前网站URL系统之外的任何手机号码或任何URL时,都会引发验证错误。

我使用下面的代码验证移动设备和URL,但是当我通过TinyMCE编辑器上传图像时,内容由带有图像URL的图像标签组成,这是我的代码失败的地方。

    function hasURL(str) {
      var res = str.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);

      return (res !== null);
    }

 $('#btnClick').click(function() {

    const PATTERN_MOBILE_INDIA = /\b([0|+[0-9]{1,5})?([7-9][0-9]{9})\b/;
    var myText = '<p><img src="https://example.com/images/image_1568090359_myimg.jpg" alt="" width="564" height="290" /></p><p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don t look even slightly believable.</p><p>9524026761</p><p>Website: https://google.com/</p><p>If you are going to use a passage of Lorem Ipsum, you need to be sure there isn t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>';
    var match = myText.match(PATTERN_MOBILE_INDIA);
    var contains = match != null;
    var hasUrl = hasURL(myText);
    var currentDomainUrl = ['https://example.com/', 'http://example.com/',
    'example.com'];

    if (contains || hasUrl) {
    	 // Check If "myText" have any image url or any url in content as the 
       // same url of current website url then no error will be thrown.
       // validation error
       alert('mobile number and url in content not allowed!');
       return false;
    }
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button id="btnClick">Check Validation</button>
</div>
javascript jquery tinymce
1个回答
0
投票

我调整了您的代码示例并对其进行了一些重组。

现在,用于匹配URL的正则表达式通过负向后扩展(?)进行扩展,这将确保其后跟的表达式仅在括号内不包含表达式的情况下才匹配(src = \“) 。

此外,找到的每个URL都将与当前域名进行比较。

// find all URL matches in <str> and return them
function findURLs(str) {
    const res = str.match(/(?<!src=\")https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g);
    console.log(res);
    return res;
}

// check if <text> contains mobile phonenumbers or urls that don't contain the current website's domain name
function validateText(text) {
    const PATTERN_MOBILE_INDIA = /\b([0|+[0-9]{1,5})?([7-9][0-9]{9})\b/;
    const hasMobileNumber = text.match(PATTERN_MOBILE_INDIA) != null;
    const urlMatches = findURLs(text);
    const currentDomainUrl = window.location.hostname;
    let valid = true;

    // check for mobile numbers
    if(hasMobileNumber) {
        valid = false;
    }

    // check for URLs
    if(urlMatches != null) {
        // check if at least one of the found URLs contain a different domain name than the current website's
        urlMatches.forEach(function(currentItem, currentIndex) {
            let domain = currentItem.replace('http://','').replace('https://','').split(/[/?#]/)[0];
            if(domain !== currentDomainUrl) {
                valid = false;
            }
       });
    }

    return valid;
}

$('#btnClick').click(function() {
    const myText = "<p><img src="https://example.com/images/image_1568090359_myimg.jpg" alt="" width="564" height="290" /></p><p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don t look even slightly believable.</p><p>9524026761</p><p>Website: https://google.com/</p><p>If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>";
    const valid = validateText(myText);

    if(valid === false) {
        alert('not ok');

        // ...
    } else {
        alert('ok');

        // ...
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.