Aivan Monceller
Aivan Monceller

Reputation: 4670

MVC data annotaion for validating data type

How do you customize data annotation validation for this scenario.

I am receiving this error:

The value 'Select Province' is not valid for Province.

I want it like this

Please select a country

My ViewModel looks like this:

    [DisplayName("Province")]
    [UIHint("ProvinceDropDown")]
    public long? ProvinceId { get; set; }

My View is a select list :

<select name="ProvinceId" id="ProvinceId" class="input-validation-error">
    <option value="">Select Province</option>
    <option value="613">Allen </option>
    <option value="614">Anderson</option>
   // data truncated ....
</select>

Upvotes: 0

Views: 665

Answers (2)

CRice
CRice

Reputation: 12567

To customize the validators you can inherit from ValidationAttribute:

public class SomeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
    public override bool IsValid(object value)
    {
    }
}

I think you won't need to do this but instead should try making your nullable long a string, and having the validators on this property.

public string ProvinceId { get; set; } 

Then converting your View Model to some domain model which has the nullable long once the validation has passed.

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180777

You need to add ErrorMessage = "Please Select a Country" to your annotation attribute, similar to the example here:

[Range(0, 50, ErrorMessage = "Quantity on order must be between 0 and 50.")]
public int OnOrder { get; set; } 

Upvotes: 2

Related Questions