简体   繁体   中英

Validating URL | Form not submitting?

Currently in my form, I have a type=text, but am trying to only accept a url in the certain component of the form.

I have tried multiple different regular expressions I found online, but it could also just be the way I am doing it. Right now, my form will not even submit. Any advice is helpful.

Note: https://, http:// are both acceptable. When a valid url is not submitted, I want to throw my error message in the HTML.

HTML Form:

<form method="POST" id="Submit">
                <div class="inner-form">
                    <div class="input-field first-wrap">
                        <div class="svg-wrapper">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                      <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z "></path>
                  </svg>
                        </div>
                        <input id="search" type="text" name="url" placeholder="Paste domain" required/>
                    </div>

                    <div class="input-field second-wrap">
                        <button id="button" class="btn-search" onclick="searchIt()" value="press" type="submit">SEARCH       </button>
                    </div>
                </div>
                    <p id="errorMessage">Yikes! That's not a valid URL. .</p>

            </form>

Javascript:

const form = document.querySelector("form");
const input = document.querySelector("input");
const button = document.querySelector("button");
const p = document.querySelector("p");

form.addEventListener("submit", (e) => {
  e.preventDefault();
  const regex = /^((https?:\/\/)?(www\.)?)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()!@:%_\+.~#?&\/\/=]*)/;

    let progress = 0;
        const maxTime = 5000; // 5 seconds
        let interval = null;
    
        let form = document.querySelector('form')
    
            function searchIt() {
    
                let form = document.querySelector('form')
                console.log(form)
    
                form.addEventListener('submit', async(e) => {
                 // onclick or the event that start the call
                    interval = setInterval(() => {
                    progress = progress >= 100 ? 100 : progress + 1
                    document.getElementById('myprogress').style.width = `${progress}%`
    
    
                // end interval and wait at 100%
                    if(progress == 100) clearInterval(interval);
                    }, maxTime/100)
                    document.getElementById('loadingcontainer').style.display = ""
                    e.preventDefault()
                    let urlIN = form.url.value
                    let url = encodeURIComponent(urlIN)
                    console.log(url)
                    try {
                        const data = await fetch('/result', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                url: url
                            })
                        }).then(res => {
                            //document.open()
                            res.text().then(function(text) {
                                 console.log(text);   
                                //document.write(text)
                                document.getElementById('result').innerHTML = text;
                                // Hide the progressbar, stop the timer and reset progress
                            clearInterval(interval);
                            progress = 0;
                            document.getElementById('myprogress').style.width = "0%"
                            document.getElementById('loadingcontainer').style.display = "none";
        
                            });
    
                        })
    
    
                    } catch (err) {
                        console.error(err)
                    }
    
                })
    
    
    
            }})

Currently, error in my console:

Uncaught ReferenceError: searchIt is not defined

在此处输入图像描述

If you are looking to validate if someone is entering a valid URL a much simpler way where you won't have to write so much code will be simply using the input type URL have a look at an example below:

<label for="url">Enter an https:// URL:</label>

<input type="url" name="url" id="url"
       placeholder="https://example.com"
       pattern="https://.*" size="30"
       required>

Link the Web Developer docs of Mozilla MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM