'How to create custom validation attribute?
I am trying to create a custom validation attribute.
public class PhoneValidator : ValidationAttribute
{
public override bool IsValid(object value)
{
return new RegularExpressionAttribute(@"^[+0]\d+").IsValid(Convert.ToString(value).Trim());
}
}
And I use this to use
[PhoneValidator]
public string PhoneNumber { get; private set; }
I copied it from a website, in theory this should work. But I couldn't make it work.
Solution 1:[1]
1-create a class for this
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MobileValidationAttribute : ValidationAttribute
{
public MobileValidationAttribute(string errorMessage)
{
ErrorMessage = errorMessage;
}
public override bool IsValid(object value)
{
if (value == null) return false;
return value.ToString().Length == 13;
}
}
2-create a model
public class UserModel
{
[Display(Name ="Phone Number")]
[MobileValidation("{0} is invalid")]
[Required(AllowEmptyStrings =false,ErrorMessage ="{0} is required")]
public string PhoneNumber { get; set; }
}
3- in view use this code
@model TestAttribute.Models.UserModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<form method="post" action="/Home/Index">
@Html.LabelFor(a=>a.PhoneNumber)
@Html.TextBoxFor(a=>a.PhoneNumber)
@Html.ValidationMessageFor(a=>a.PhoneNumber)
<br />
<br />
<button type="submit">Add</button>
</form>
</div>
</body>
</html>
4- and Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new UserModel());
}
[HttpPost]
public ActionResult Index(UserModel model)
{
if (ModelState.IsValid)
{
return Content("Ok");
}
return View(model);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diako Hasani |
