简体   繁体   中英

validate multiple URL input fields

I have following Javascript validation function that should check that the URL posted to my php are OK - if not display a message to correct the entry. I must have done a mistake somewhere because it is not working and my console.log says: ReferenceError: Can't find variable: $ validateFormbasic.html:12 onsubmitbasic.html:24:95 Could you tell me how to fix it please? Thanks a lot!

<form method="POST" name="inputLinks" onsubmit="return validateForm();">
<input type="text" name="web1" id="url1" placeholder="domain.com">
<input type="text" name="web2" id="url2" placeholder="domain.com">
<input type="text" name="web3" id="url3" placeholder="domain.com">
<input type="submit" name="Submit" value="Done" />   
</form>

<script type="text/javascript">
function validateURL(web1, web2, web3) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}

function validateForm()
{
// Validate URL
var url = $("#url1", "#url2", "#url3").val();
if (validateURL(url)) { } else {
    alert("Please enter a valid URL, remember including http://");
}
return false;
}
</script>

As Alberto's comment mentions, it looks like jQuery isn't loaded at the point of calling the function. It also looks to me as if you're syntax for selecting the URL values isn't quite right.

I would use something along the lines of:

<form method="POST" name="inputLinks">
<input type="text" name="web1" id="url1" class="url" placeholder="domain.com" />
<input type="text" name="web2" id="url2" class="url"  placeholder="domain.com" />
<input type="text" name="web3" id="url3" class="url"  placeholder="domain.com" />
<input type="submit" name="Submit" value="Done" />   
</form>

<script type="text/javascript">

    $(function(){

        function validateURL(url) {
            var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
            return reurl.test(url);
        }

        $('form').submit(function(e){

            var isValid = true;

            $('.url').each(function(){
               isValid = validateURL($(this).val());
               return isValid;
            });

            if (!isValid){
                e.preventDefault();
                alert("Please enter a valid URL, remember including http://");
            }

        });

    });

</script>

Update

Demo JS Fiddle

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