Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation Plugin - remove 'http://' requirement with URL's

I'm looking to validate a URL without requiring the user to enter "http://". How it is in the form below, "http://" must be entered for the form to be submitted. I can't figure out how to do this. Any help would be much appreciated.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and a url.</title>
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/site-demos.css">

</head>
<body>
<form id="myform">
<label for="field">Required, URL: </label>
<input class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      url: true
    }
  }
});
</script>
</body>
</html>

Edit: Took isherwood's advice:

    var txt = $('#website').val();

    var http = txt.indexOf('http://');

    if (http > -1) {
        $('#website').val(txt);
    } else {
       $('#website').val('http://' + txt);
    }
like image 910
Tim Aych Avatar asked Jan 23 '26 13:01

Tim Aych


1 Answers

Why not add it to the URL for your users? A URL isn't a URL without a protocol anyway (the exception being protocolless URLs, but they still have '//').

$('#myform').on('submit', function() {
    var myURL = 'http://' + $('#field').val();
    $('#field').val(myURL);
});
like image 129
isherwood Avatar answered Jan 26 '26 02:01

isherwood