Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

html - Custom validation message on 'type=url'

I am using type=url in my form to only allow a url to be passed through.

However, using the standard validation message is as follows enter image description here

Is there a way to change this? Here is the design what I am trying to achive (outline search bar, add message beneath, and make text in search box orange)

enter image description here

Here is function after my 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('/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            url: url
                        })


                    }).then(res => {
                        document.open()
                        res.text().then(function(text) {

                            document.write(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)
                }

            })


        }
question from:https://stackoverflow.com/questions/65929612/custom-validation-message-on-type-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Rather than write all the necessary validation for URLs, you can use the HTML5 input type "url" in place of type "text", which has all that validation built in:

<input type="url" name="location">

That will require a properly formed URL, but ftp:// is also proper. You can further constrain it by using the pattern attribute for your requirements "beginning in http://, https://, includes www.".

Here, using novalidate on the <form_> prevents the browser from showing it's own messages, then you can test a field's validity with field.checkValidity()

const urlField = document.getElementById('onlyweb');
const messagebox = document.getElementById('errormessage');

document.getElementById('testform')
        .addEventListener('submit', function(e) {
            e.preventDefault();
            const valid = urlField.checkValidity();
            console.log('valid =', valid);
            if (valid) {
                messagebox.innerHTML = ''; // clear any message that might be there
                messagebox.classList.add('hidden');
            }
            else {
                messagebox.innerHTML = '<span class="errmsg">You need to include http:// or https:// and include the "www." prefix.</span>';
                messagebox.classList.remove('hidden');
            }
        });
input:invalid {
  border-color: red;
}
div {
  margin-bottom: 1em;
}
#errormessage {
  font-family: sans-serif;
  color: red;
  border: 1px solid gray;
  padding: 1em;
}
#errormessage.hidden {
  display: none;
}
<form id="testform" action="#" novalidate>
<div>
Invalid fields will have a red border
</div>
<div>
  <label for="onlyweb">Only Web URLs</label>
  <input type="url"
         name="onlyweb" id="onlyweb"
         pattern="^https?://www..*$"
         >
</div>
<div>
  <input type="submit" value="Test It">
</div>
<div id="errormessage" class="hidden">
</div>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...