I have a Model similar to the following
public class TaskModel
{
public int UserId { get; set; }
public int CustomerId { get; set; }
public string CustomerDescription { get; set; }
/* Snip */
}
How can I add validation to ensure that, on client-side, a hidden field representing the CustomerId is greater than zero?
@Html.LabelFor(x => x.CustomerId)
@Html.HiddenFor(x => x.CustomerId)
<label id="customerName" class="description">
@Model.CustomerName
</label>
Just to explain what’s going on above; I use a popup to select a customer from a list, which then populates the hidden field with the ID of the customer and updates the label description to the customer that the ID represents. I do it that way to avoiding an unnecessary post & database call.
I don’t want to have to post the form data to determine if the ID is greater than 0. Is there an easy way to add this as both an Attribute to the Model and have it handled client side? I’ve written the following Validation attribute, but I don’t know how to make it work seemlessly on the client-end as well.
public class ValidIDAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
{
return false;
}
else
{
if (value.GetType() == typeof(int))
{
return (int)value > 0;
}
else if (value.GetType() == typeof(Guid))
{
return (Guid)value != Guid.Empty;
}
return false;
}
}
}
You can use the built-in
Rangeattribute:This includes unobtrusive client-side validation.
To create custom client-side validator, see this article.