3

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);
    }
1

2 Answers 2

6

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);
});
Sign up to request clarification or add additional context in comments.

Comments

1

you can use addmethod with REGEX, just add the class from the method to your input http://jqueryvalidation.org/jQuery.validator.addMethod/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.