Add error message to @Html.ValidationSummary

后端 未结 2 647
梦如初夏
梦如初夏 2021-02-02 09:47

I\'m using standard MVC3 Razor views with unobtrusive Javascript validation, using @Html.ValidationSummary to show them at the top of the form. If the standard vali

相关标签:
2条回答
  • 2021-02-02 10:23

    You can do so just adding the Error Message to the ModelState should display the error message for you, provided that you have ValidationSummary() called on your view.

    To add the error to the ModelState just do this:

    ModelState.AddModelError("ColumnNameOrErrorMessageKeyInState","error message goes here")
    
    0 讨论(0)
  • 2021-02-02 10:32

    In client-side:

    function YourCustomValidator() {
        // do your validation logic here via JavaScript
        return true; // or false based on your validation logic
    }
    $(document).ready(function () {
        // take your own form-selector like ("form", this)
        $("form", this).first().submit(function () {
            return (YourCustomValidator() && $(this).valid());
        });
    });
    

    OR In server-side:

    Think you have a model like this:

    public class Test {
        [Required]
        [StringLength(100)]
        public string FullName { get; set; }
    }
    

    and when you are validating it:

    if(ModelState.IsValid) { // default validations run here
        if(/* some custom validations run here, there is an error about "FullName" */){
            // you should set the "key" for Model-Error to "FullName"
            ModelState.AddModelError("FullName","error-message goes here")
        }
        if(/* some custom validations run here, the error is global, not on "FullName" */){
            // you should set the "key" for Model-Error to an empty-string
            ModelState.AddModelError("","error-message goes here")
        }
        // also you can test for model-errors again like this:
        if(ModelState.IsValid) { // if you add any error above, this will be "false"
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题