Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate URL without http:// [duplicate]

I'm trying to validate a url without http:// using jQuery validate but it's not working. I am following the mtosic's answer from here

<form id="form" method="post" action="#">
    <input type="text" name="url" id="url" />
    <button type="submit">Submit</button>
</form>

  $.validator.addMethod('validUrl', function(value, element) {
    var url = $.validator.methods.url.bind(this);
    return url(value, element) || url('http://' + value, element);
  }, 'Please enter a valid URL');

$("#form").validate({
  rules: {
    "url": {
      url: "validUrl"
    }
  },
  submitHandler: function (form) { 
    alert('valid form submitted'); 
    return false; 
  }
});

When I type in an address like "www.google.com" I still get the invalid error.

Here's the fiddle

What is the issue? Thank you for the help

like image 268
cpcdev Avatar asked Jul 16 '26 15:07

cpcdev


1 Answers

The problem is because you've defined the rule named validUrl, yet you're still setting the url rule on the element in the $.validate settings. Also note that you want to pass a boolean value to the property, not a string. Try this:

$(document).ready(function() {
  $.validator.addMethod('validUrl', function(value, element) {
    var url = $.validator.methods.url.bind(this);
    return url(value, element) || url('http://' + value, element);
  }, 'Please enter a valid URL');

  $("#form").validate({
    rules: {
      "url": {
        validUrl: true // <-- change this
      }
    },
    submitHandler: function(form) {
      alert('valid form submitted'); // for demo
      return false; // for demo
    }
  });
});
body {
  padding: 20px;
}

label {
  display: block;
}

input.error {
  border: 1px solid red;
}

label.error {
  font-weight: normal;
  color: red;
}

button {
  display: block;
  margin-top: 20px;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
  <input type="text" name="url" id="url" />
  <button type="submit">Submit</button>
</form>
like image 86
Rory McCrossan Avatar answered Jul 19 '26 03:07

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!