1

I'm trying to set a validation rule for a int value in my model.

The value can only be 1 , 2 or 4. so i cant use a range validation rule. How should i validate if the number is valid ?

i could not find anything but range, so unfortunately i don't have anything yet.

3
  • 2
    What do you have so far? Can you show the code? Commented Oct 21, 2014 at 16:41
  • 1
    You can write your own validation attributes, implement IValidatableObject, or use a regular expression. Those are all the approaches I can think of, anyway. Commented Oct 21, 2014 at 16:43
  • Also, you can validate the object in your POST function (if you have such one) or I think there is a way to validate this in javascript - but the its vulnerable. Commented Oct 21, 2014 at 16:47

3 Answers 3

2

Something like

[RegularExpression("[124]", ErrorMessage = "Value must be 1, 2 or 4")]
public int Value{ get; set; }
Sign up to request clarification or add additional context in comments.

1 Comment

Nice and simple great !
1

The RegularExpression validator with a valid set of values [124] is the obvious option.

However, i have found an interesting alternative that has definitely better performance than the RegularExpression validator. The idea is to use an EnumDataType validator with valid values for the integers:

[EnumDataType(typeof(ValidValues), ErrorMessage = "Valid values are 1,2,4")]
public int ReqValue { get; set; }

public enum ValidValues
{
    First = 1,
    Second = 2,
    Fourth = 4
}

Comments

0

Add this code to your project: Get the "Key" for a strongly typed model in the controller

Then add a method which performs the validation, say, void Validate(YourModelType model).

Finally, in your POST action, put something like this:

Validate(model);

if (ModelState.IsValid) {
    //valid, do whatever actions you need
    return RedirectToAction("whatever");
}

return View(model); //show the page again

1 Comment

Keep in mind, this does not enable any client-side validation. I tend to use this method for more complex things that are database-dependent. It just also happens to be simple enough for what you want, while still integrating with MVC's server-side validation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.