javascript 对客户端错误消息使用 html.validationmessagefor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29707061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:56:40  来源:igfitidea点击:

Using a html.validationmessagefor for a client side error message

javascriptjqueryhtmlasp.net-mvcclient-side-validation

提问by user1186050

I have server side validation messages for some of my text fields. The field 'title' is a required field server side with a '[Required]' data attribute in the class, but this only seems to get checked on a postback or form submit. I'm saving the 'title' text field on a jquery .change event, sudo code below. But I want to use my validationmessagefor to show the error message from the client side check. Not sure how to go about doing this?

我有一些文本字段的服务器端验证消息。字段“title”是必需的现场服务器端,在类中具有“[Required]”数据属性,但这似乎只在回发或表单提交时进行检查。我正在 jquery .change 事件上保存“标题”文本字段,sudo 代码如下。但我想使用我的validationmessagefor 来显示来自客户端检查的错误消息。不知道该怎么做?

html.

html。

@Html.ValidationMessageFor(model => model.Overview.Title, "", new { @class = "text-danger" })

rendered as

呈现为

<span class="field-validation-valid text-danger" data-valmsg-for="Overview.Title" data-valmsg-replace="true"></span>

If I want to do some client side checking in javascript and then use this element to display a client side error message can I do so. I'm just trying to save myself of using another hidden element. I know I would have to use

如果我想在 javascript 中进行一些客户端检查,然后使用此元素显示客户端错误消息,我可以这样做。我只是想避免使用另一个隐藏元素。我知道我将不得不使用

data-valmsg-for="Overview.Title"

data-valmsg-for="Overview.Title"

because the other data attributes are the same for all the other text fields.

因为其他所有文本字段的其他数据属性都相同。

Whats the best way to do display client side error messages here if I want to check to make sure the "title" has length greater then 1?

如果我想检查以确保“标题”的长度大于 1,那么在此处显示客户端错误消息的最佳方法是什么?

Maybe something like -

也许像 -

$('#Overview_Title').change(function() {
    var title = $(this).val();
    if (title.length == 0) {
      // show error message "title has to be a value to save"
      }
    else {
      // do other work like save to db
      }
  });

采纳答案by Rondel

You've got a few ways to do this but I'd argue that this is the easiest way:

您有几种方法可以做到这一点,但我认为这是最简单的方法:

MVC will by default bundle the jquery.validatejavascript library into your page. Since you are already marking the field with the [Required]attribute, the Html.EditorForwill bind the correct attributes into your HTML for you so that validation can happen as necessary.

默认情况下,MVC 会将jquery.validatejavascript 库捆绑到您的页面中。由于您已经使用[Required]属性标记字段,因此Html.EditorFor将为您将正确的属性绑定到您的 HTML 中,以便在必要时进行验证。

To make your current logic work with the smallest changes, you could add a <form>tag around your input field(s). I think you need this for the validatemethod to work out of the box. Then your javascript would change to something like this:

为了使您当前的逻辑以最小的更改工作,您可以<form>在输入字段周围添加一个标签。我认为你需要这个validate方法才能开箱即用。然后你的 javascript 会变成这样:

$('#Overview_Title').change(function() {
if ($(this).valid()) {
  // do your stuff
  }
else {
  // error message displayed automatically. don't need to do anything here unless you want to
  }
});

This would allow you to use the Requiredattribute to set your error message text and your ValidationMessageForshould display the error message without any extra effort on your part.

这将允许您使用该Required属性来设置错误消息文本,并且您ValidationMessageFor应该无需任何额外的努力即可显示错误消息。

Check out this plunkr as a proof of concept: http://plnkr.co/edit/ip04s3dOPqI9YNKRCRDZ?p=preview

看看这个 plunkr 作为概念证明:http://plnkr.co/edit/ip04s3dOPqI9YNKRCRDZ?p=preview

EDIT

编辑

I'm not positive I understand your follow-up question. But if you wanted to add a rule to a field dynamically, you could do something along these lines:

我不肯定我理解你的后续问题。但是,如果您想动态地向字段添加规则,您可以按照以下方式进行操作:

$( "#someinput" ).rules( "add", {
 required: true,
 messages: {
 required: "a value is required to save changes"
 }
});

You could add rules that aren't reflected server side by doing something like this. Then you could validate that input in the same way.

您可以通过执行此类操作来添加未反映服务器端的规则。然后您可以以相同的方式验证该输入。

回答by IndieTech Solutions

If you want to do 100% client side validation using jquery you can use something like this:

如果您想使用 jquery 进行 100% 客户端验证,您可以使用以下内容:

$('#Overview_ISBN').on('input', function() {
    var input=$('#Overview_Title');
    var is_name=input.val();
    if(is_name){input.removeClass("invalid").addClass("valid");}
    else{input.removeClass("valid").addClass("invalid");}
});

Here's the code of JSFiddle link

这是JSFiddle链接的代码

In the example i posted , if you start typing the ISBN and the Title is empty, you will get the error message.

在我发布的示例中,如果您开始输入 ISBN 并且标题为空,您将收到错误消息。

Not sure in your question how you want to trigger the error so i assumed it's an entry in a different input

在你的问题中不确定你想如何触发错误,所以我认为它是不同输入中的一个条目