Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC DataAnnotations URL validation

I'm using ASP.NET MVC3 and trying to validate an URL field using DataAnnotationsExtensions.

It's almost what I need. However, it forces the user to add "http://" at the beggining of the URL string, if not, it will show the following validation message:

The URL field is not a valid fully-qualified http, https, or ftp URL.

In the Data Annotations Extensions URL demo page it shows an additional validator UrlWithoutProtocolRequired, but I cannot find it anywhere.

How can I use this validator, or how can I easily validate the URL without the "http://" part?

like image 801
Nelson Reis Avatar asked Aug 19 '11 23:08

Nelson Reis


People also ask

What does ModelState IsValid validate?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.

Can we do validation in MVC using data annotations?

In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.


1 Answers

The protocol-less option for DataAnnotationsExtensions is available in the source code but is considered beta or "vNext" and hasn't been released as part of the NuGet package. So if you download the source and compile you'll see the [Url] attribute has an overload [Url(requireProtocol: false)]. You can see this in the latest UrlAttribute.cs file (UrlArribute.cs). Also if you look in the DataAnnotationsExtensions wiki you'll see this feature is scheduled to be released soon (I'm thinking in the next week or two for an official next release).

like image 88
Scott Kirkland Avatar answered Nov 13 '22 13:11

Scott Kirkland