Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:)

like image 314
SidC Avatar asked Dec 20 '22 21:12

SidC


1 Answers

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; }
like image 110
SalmanAA Avatar answered Jan 08 '23 04:01

SalmanAA