Server side validation is done with data annotations instead of doing client side validation

前提是你 提交于 2019-12-24 17:28:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!