Issue with implementation of JS URL form validation (beginner)
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I'm having some trouble adding a full URL validation to my script.
I want to replace the

  if(fields[i] === 'location' && value.toLowerCase().indexOf('http') !== 0)

with something like that (this doesn't work though)

  var regex = /^(http[s]?:\/\/(www\.)?|ftp:\/\/(www\.)?|www\.){1}([0-9A-Za??-z-\.@:%_\+~#=]+)+((??\.[a-zA-Z]{2,3})+)(\??/(.)*)?(\?(.)*)?/g;
var revurl = document.getElementById('location').value;
if(!regex.test(revurl)){
        errors.push('- URL non valide');
        is_valid = false;
    }

Thanks. And here is the code.

function isValidForm(){

var fields = ['summary', 'review', 'location'];
var messages = ['- titre', '- avis', '- site web'];
var is_valid = true;
var errors = [];
var elmform=$('#reviewformsubmit');
for(var i = 0; i < fields.length; i++){
    var value = elmform.find('[name=' + fields[i] + ']').val();

    if(value.length === 0){
        errors.push(messages[i]);
        is_valid = false;
        }else if(fields[i] === 'location' && value.toLowerCase().indexOf('http') !== 0){
        errors.push(messages[i]);
        is_valid = false;
    }
}


if(is_valid){

    if(!is_valid)
        alert('Merci de compléter le(s) champs suivants :\n'+errors.join('\n'));
    else
        $('#reviewformsubmit').submit();


}else{

    alert('Merci de compléter le(s) champs suivants :\n'+errors.join('\n'));

}
}
awarded to weslly

Crowdsource coding tasks.

1 Solution

Winning solution

This should work:

function isValidForm(){

    var fields = ['summary', 'review', 'location'];
    var messages = ['- titre', '- avis', '- site web'];
    var is_valid = true;
    var errors = [];
    var elmform=$('#reviewformsubmit');


    var url_regex = new RegExp(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi);

    for(var i = 0; i < fields.length; i++){
        var value = elmform.find('[name=' + fields[i] + ']').val();

        if(value.length === 0){
            errors.push(messages[i]);
            is_valid = false;
            } else if(fields[i] === 'location' && !value.match(url_regex)){
            // errors.push(messages[i]);
            errors.push('- URL non valide');
            is_valid = false;
        }
    }

    if(is_valid){

        if(!is_valid)
            alert('Merci de compléter le(s) champs suivants :\n'+errors.join('\n'));
        else
            $('#reviewformsubmit').submit();

    } else{

        alert('Merci de compléter le(s) champs suivants :\n'+errors.join('\n'));

    }
}
Perfect, thanks :)
Benoit 4 months ago
View Timeline