简体   繁体   English

如何使用Asp.NET 4.5和Razor视图(非MVC)添加自定义验证消息

[英]How to add custom validation message using Asp.NET 4.5 and Razor view (Not MVC)

I have an ASP.NET 4.5 Web Site project which is using Razor views. 我有一个使用Razor视图的ASP.NET 4.5网站项目。 This is not an MVC project, it is an empty web site with just a few .cshtml files in it. 这不是MVC项目,它是一个只有几个.cshtml文件的空网站。

I have a form where I want to validate. 我有一个要验证的表格。 I found a site here that explains how to do this with a Razor view, but the Validation class does not have the methods shown in the example. 我在这里找到一个站点,该站点解释了如何使用Razor视图执行此操作,但是Validation类没有示例中显示的方法。 I then came across the required attribute in HTML5, and I added that to each <input> in my form. 然后,我在HTML5中遇到了required属性,并将其添加到表单的每个<input>中。 This is validating the form when I submit it, but it is using generic error messages like shown in the image: 当我提交表单时,这是对表单的验证,但是它使用的是通用错误消息,如图所示:

在此处输入图片说明

Here are my questions: 这是我的问题:

Is there some way to customize these messages? 有一些自定义这些消息的方法吗?

Is there some way to validate other requirements besides required - like making sure its a number, or a certain length, etc? 有没有一些方法来验证除其他要求required -例如确保它的一个数字,还是有一定的长度,等等?

*Note** I am not using MVC, so no models, etc. I also was trying to use something built in to ASP.NET if possible, and not use jQuery Validation directly. *注意**我没有使用MVC,所以没有模型,等等。如果可能的话,我也试图使用内置于ASP.NET的东西,而不直接使用jQuery Validation。

Thanks in advance! 提前致谢!

You can set your custom message with data-val-required attribute. 您可以使用data-val-required属性设置自定义消息。

Make sure you added the jquery validation and Microsoft jquery unobstrustive js file in your page. 确保在页面中添加了jquery validationMicrosoft jquery unobstrustive js文件。

Below are the example. 以下是示例。 You can mix all data-val attributes and achieve all your combination 您可以混合所有data-val属性并实现所有组合

Example 1: Required, length 示例1:必需,长度

<input type="text" value="" name="UserName" id="checking-user" 
 data-val="true"
 data-val-required="The UserName field is required." 
 data-val-length-max="100" 
 data-val-length="The field UserName must be a string a maximum length of 100." 
 />

Example 2: Required, Number and Regex 示例2:必需,数字和正则表达式

<input type="text" value="" name="PaidAmount" 
   data-val="true" 
   data-val-required="Amount is required" 
   data-val-regex-pattern="[-+]?[0-9]*\.?[0-9]?[0-9]" 
   data-val-regex="Amount should be in numbers" 
   data-val-number="The field PaidAmount must be a number." 
   />

Yeah you can do a lot of validation with HTML5 only 是的,您只能使用HTML5进行很多验证

Along with the text input type, there are now a host of other options, including email, url, number, tel, date and many others. 除文本输入类型外,现在还有许多其他选项,包括电子邮件,URL,数字,电话,日期和许多其他选项。

You can use setCustomValidity to customize messages and whatnot. 您可以使用setCustomValidity来自定义消息等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM