[英]Data Annotations for multiple validation types
I feel like this should be so simple. 我觉得这应该很简单。 I need to validate a decimal value with a range of (0 - 99.999999) OR I need to be able to mark the value with "TBD".
我需要验证范围为(0-99.999999)的十进制值,或者需要能够用“ TBD”标记该值。 I have no way to change that requirement or I may have done it another way.
我无法更改该要求,或者我可能已经做了另一种方式。 Is there a way to handle multiple validation types through data annotations?
有没有一种方法可以通过数据注释来处理多种验证类型? I suck at regex.
我在正则表达式上很烂。 If this can be done that way, can anyone point me in the right direction?
如果可以那样做,谁能指出我正确的方向?
I think I clicked on this from a C# tag, but I don't see any tags in the post. 我想我是从C#标签上单击的,但是在帖子中没有看到任何标签。 Regardless my code is in C# and in a Win Forms app.
无论我的代码是在C#中还是在Win Forms应用程序中。
I am not sure what you mean by 'TBD' but this will be valid for any input of a number between 00.000000 and 99.999999. 我不确定“ TBD”是什么意思,但这对于任何在00.000000到99.999999之间的数字输入都有效。 Note that this will allow two values to the left of the decimal, ie, '09.1'.
请注意,这将允许小数点左边两个值,即“ 09.1”。
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace RegexInputValidation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBoxInput_TextChanged(object sender, EventArgs e)
{
string regex = @"^((\d{0,2}(\.\d{1,6})?)|(\.\d{1,6}))$";
bool isValid = (Regex.IsMatch(textBoxInput.Text, regex) && !textBoxInput.Text.Contains(" ") && !textBoxInput.Text.Equals(""));
if (isValid)
textBoxValid.Text = "Valid input: " + double.Parse(textBoxInput.Text);
else
textBoxValid.Text = "TBD";
}
}
}
So, Jerodev was correct. 因此,耶罗杰夫是正确的。 This could not be properly done with a Data Annotation.
使用数据注释无法正确完成此操作。 I had to create a custom validator and then implement the validator in a new Data Annotation of my own.
我必须创建一个自定义验证器,然后在自己的新数据注释中实现该验证器。 I followed http://ezzylearning.com/tutorial/creating-custom-validation-attribute-in-asp-net-mvc to learn how to create my own custom validator.
我遵循了http://ezzylearning.com/tutorial/creating-custom-validation-attribute-in-asp-net-mvc来学习如何创建自己的自定义验证器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.