Here’s the situation: I have a great big text input box for a URL here: https://asafaweb.com
This doesn’t need to adhere to the strict definition of a URL though; I allow addresses without a scheme then default to HTTP for usability purposes. For example, “stackoverflow.com” would be considered a valid URL. But there are also URLs which I don’t want to allow for various reasons (i.e. they’ve been blacklisted or they’re internal IP address ranges).
I want to set the type of the input to “url” rather than the default “text” so users on mobile devices get a keyboard designed for the URL context (i.e. iOS gives you a “.com” button), The problem is that as soon as I do this, the default unobtrusive jQuery validation bundled with ASP.NET MVC expects a URL with a scheme thus breaking my schemeless URL support.
This is an MVC4 site and I have an HTML helper like so:
@Html.TextBoxFor(m => m.ScanUrl, new { type = "url" })
The ScanUrl attribute then has a custom ValidationAttribute which does all the bespoke checks to make sure that URL can be scanned.
How can I keep the existing validation pattern without jQuery validation interjecting and wanting to make sure a URL is, well, a strict URL?
If you don’t need the strict URL validation anywhere in this site, modifying how jQuery Validation validates URLs might be the easiest way to handle that. You’ll find that on line 1034 of jquery.validate.js if you’re using the version that ships with MVC 4.
You could tweak the regex right there in the plugin script, or you could patch the url validation method after jQuery Validation is loaded:
The main advantage to patching it afterward being that you aren’t tied to your tweaked version of the script and could update jQuery Validation itself later without losing your customized url validator. That’s probably obvious to you, but may be helpful to others finding this answer later.