0

I'm new to JS and couldn't find the answer anywhere in the web so I got to ask here !

I want to check if the input contains one of the substring in an array, if not, form submission got to be stopped right away and page load avoided.

**Inputs examples:**
"http//:www.indeed.com" IS validated  --- 
"http//:www.linkedin.com" IS validated  --- 
"http//:www.google.com" IS NOT validated  ---

        <form name="form1" action="index.php" method="post">
        <input id="link" required type="text" name="link">
        <button type="submit" onsubmit="javascript:checklink();" class="submit">
        go ! 
        </button>               
        </form>

        function checklink() {
            var arr = ['indeed.', 'linkedin.'];
            var i;
            var input = document.getElementById("link").value;
            for (i = 0; i < arr.length; i++) {
                 if ( arr[i] !== input) {
                    alert(arr[i] +"Wrong URL");
                    return false;
                }
                else {return true}
            }
        }

Any idea ? Thanks a lot in advance !

Hymed Ghn
  • 1
  • 2
  • You're checking if a string includes another string. Similar question here - https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript – Chris Camaratta Oct 05 '20 at 13:11
  • `var exists = false; arr.forEach(validator => { if (input.includes(validator)) { exists = true } })` – siddhant sankhe Oct 05 '20 at 13:14
  • @siddhantsankhe thanks for your hint ! I tried this option, but it actually checks all array item. Which mean that if the input contains only one of the items, 'exists =false' one time and the alert message will be triggered ... – Hymed Ghn Oct 05 '20 at 13:33
  • @siddhantsankhe see the fiddle here : https://jsfiddle.net/yd04puq7/ – Hymed Ghn Oct 05 '20 at 13:38
  • @HymedGhn https://jsfiddle.net/siddhantsankhe/djvazx21/ check this ive made few changes – siddhant sankhe Oct 06 '20 at 10:30

0 Answers0