C# 检查用户输入是否以两种可能性之一开始

C# 检查用户输入是否以两种可能性之一开始,c#,asp.net-mvc,asp.net-mvc-5,C#,Asp.net Mvc,Asp.net Mvc 5,我有一个页面,客户将输入某些数据,但是,在其中一个字段中,输入只能以“SWG…”或“MH…”开头。除此之外,SWG后面应包含7个数字,MH后面应包含5个数字 我是新来的,所以任何帮助都将不胜感激。我的代码如下 public partial class VehicleRegistration { [Required] [Display(Name = "User Email:")] public string User_Email { get; set; } [R

我有一个页面,客户将输入某些数据,但是,在其中一个字段中,输入只能以“SWG…”或“MH…”开头。除此之外,SWG后面应包含7个数字,MH后面应包含5个数字

我是新来的,所以任何帮助都将不胜感激。我的代码如下

public partial class VehicleRegistration
{
    [Required]
    [Display(Name = "User Email:")]
    public string User_Email { get; set; }


    [Required] //This is the section where input should only begin with MH or SWG
    [Display(Name = "Serial No:")] 
    public string Serial_No { get; set; }

    [Required] 
    [StringLength(16, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 16)]
    [Display(Name = "Control Panel M Number:")]
    public string IMEI_No { get; set; }

 }
这里的最后一个字段是用于设置输入长度的字段。 我还有一个cshtml页面,其中包含以下代码

<div class="form-group">
    @Html.LabelFor(model => model.Serial_No, htmlAttributes: new { @class = "control-label col-md-4" })
    <div class="col-md-8">
        @Html.EditorFor(model => model.Serial_No, new { htmlAttributes = new { @class = "form-control", @placeholder = "Required" } })
        @Html.ValidationMessageFor(model => model.Serial_No, "", new { @class = "text-danger" })
    </div>
</div>

@LabelFor(model=>model.Serial_No,htmlAttributes:new{@class=“controllabel col-md-4”})
@EditorFor(model=>model.Serial_No,new{htmlAttributes=new{@class=“form control”,@placeholder=“Required”})
@Html.ValidationMessageFor(model=>model.Serial_No,“,new{@class=“text danger”})

您正在寻找一个名为Regex的系统

在你的情况下,解决办法是

if(Regex.IsMatch(myText, @"^SWG\d{7}$|^MH\d{5}$"))
{
    //myText is valid
}
在MVC中,字段看起来像

[Required]
[RegularExpression(@"^SWG\d{7}$|^MH\d{5}$", ErrorMessage="Serial number must be SWG####### or MH#####")]
[Display(Name = "Serial No:")] 
public string Serial_No { get; set; }

您可以看到正则表达式工作原理的分解。

您可以在MVC中添加正则表达式验证,如下所示:

[RegularExpression("SWG\d{7}|MH\d{5}", ErrorMessage = "Invalid input")]
[Required] //This is the section where input should only begin with MH or SWG
[Display(Name = "Serial No:")] 
public string Serial_No { get; set; }

但是,如果您需要更复杂的验证逻辑,请尝试了解更多有关远程验证的信息。

我觉得这像wpf,请以后添加“wpf”标记。我觉得这不像wpf,以后请不要添加“wpf”标记。添加一些其他标记。谢谢。@Rariolu这是一个MVC项目。我很抱歉。不过,标签还是很有用的。@Rariolu我向您道歉,您可以看到我对这一点还不熟悉。正确方向的指针是值得赞赏的。我现在已经为代码添加了标签。它是Regex而不是Regex,您需要对这些反斜杠进行划界,或者通过在其前面添加@使模式成为逐字字符串。如果你想要一个
bool
而不是
匹配项,你应该调用
IsMatch
。最后,模式是第二个论点。@juharr我修正了错误(太多的语言在我的大脑中游荡),但分组不是必需的,至少在.net中是这样(我测试过)。我还添加了
^
$
,当时我注意到
MH1234567
会匹配。@RoadieRich非常感谢,这非常有效。我学到了一些新东西。