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:)
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\-\.\?\,\'\/\\\+&%\$#_]*)?$")
{}
}
so on the model:
[Url(ErrorMessage = "URL format is wrong!")]
public string BlogAddress { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With