SidC
SidC

Reputation: 3213

How to Implement MVC3 Model URL Validation?

I've successfully implemented client side validation to require input in my textbox. However, I want to evaluate the contents of the textbox to see if it is a well formed URL. Here's what I have thus far: Index.cshtml:

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>
@model Ticket911.Models.ValidationModel                          
@{
ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
@using (Ajax.BeginForm("Form", new AjaxOptions() { UpdateTargetId = "FormContainer" , OnSuccess = "$.validator.unobtrusive.parse('form');" }))

{
<p>
    Error Message: @Html.ValidationMessageFor(m => m.URL)
</p>
<p>
@Html.LabelFor(m =>m.URL):
@Html.EditorFor(m => m.URL)
</p>
<input type="submit" value="Submit" />

ValidationModel:

 public class ValidURLAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return (value != null);
    }
}

public class ValidationModel
{
    [Required]
    public string URL {get; set;}
}

How do I ensure that the model URL validation occurs? When the Submit button is clicked, what must be done to navigate to the URL entered into the textbox?

Thanks much:)

Upvotes: 4

Views: 6381

Answers (2)

Shyju
Shyju

Reputation: 218832

You can do it wtih DataAnnotations

public class ValidationModel
{
  [Required]
  [RegularExpression(@"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$", ErrorMessage = "URL format is wrong")]
  public string URL {get; set;}
}

And in your HTTPPost Action method, You can call the ModelState.IsValid property which will check the Validations for you.

[HttpPost]
public ActionResult Save(ValidationModel model)
{
  if(ModelState.IsValid)
  {
   //Save or whatever
  }
  return View(model);

}

Upvotes: 6

SalmanAA
SalmanAA

Reputation: 552

good way is to implement your attribute for next use in mvc projects. like this:

public class UrlAttribute : RegularExpressionAttribute
{
    public UrlAttribute() : base(@"^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$")
    {}
}

so on the model:

[Url(ErrorMessage = "URL format is wrong!")]
public string BlogAddress { get; set; }

Upvotes: 6

Related Questions