问题
while I was working with validation in MVC, and I wrote a custom attribute to validate a property.Initially the client side validation was not working since attribute was not registered.When i clicked on the save
button after contacting the server it was showing the error message.So can anyone tell how this server side validation took place instead of client side validation ?
attribute usage ->
[PhoneNumberHasPlus(ErrorMessage="Invalid number")]
public string PhoneNumber {get;set;}
attribute ->
public class PhoneNumberHasPlusAttribute : RegularExpressionAttribute
{
public PhoneNumberHasPlusAttribute() :
base(@"^[+][0-9' '\.\-\(\)]{10,20}$") { }
public override string FormatErrorMessage(string name)
{
if (String.IsNullOrEmpty(ErrorMessage))
ErrorMessage = "PhoneNumberWithPlus";
return ErrorMessage;
}
}
回答1:
You have to have a Model.IsValid in your action. That element turns on the validation.
public ActionResult Create(Model model) {
if (ModelState.IsValid) {
// logic
}
return View(dinner);
}
Please make sure that your view contains correct path to jQuery libraries
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
Also your have to use this Razor syntax to generate correct html
@Html.EditorFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
Here you can find a full tutorial of adding validation to the MVC Model.
回答2:
You need to include jquery Val bundle into your view like this
@section scripts
{
@Scripts.Render("~/bundles/jqueryVal")
}
来源:https://stackoverflow.com/questions/34940878/server-side-validation-is-done-with-data-annotations-instead-of-doing-client-sid