c# - 允许字符输入的正则表达式检查

标签 c# regex asp.net-mvc

我使用 Remote 对农场模型进行数据验证并检查省代码我不断收到不接受两个字符的错误。我需要省代码为 2 个字母长并检查它们是否真的字母。这是 RemoteController 的代码:

public JsonResult provinceCodeCheck(string provinceCode)
{
    Regex justLetters = new Regex("^[A-Z]$");
    provinceCode.ToUpper();
    var provinceCodes = db.provinces.Find(provinceCode);

    if (provinceCode.Length != 2)
    {
        return Json("The Province must be 2 letters long",
           JsonRequestBehavior.AllowGet);
    }
    else if (!justLetters.Equals(provinceCode))
    {
        return Json("The Province is not letters",
           JsonRequestBehavior.AllowGet);
    }
    else if (provinceCodes == null)
    {
        return Json("The Province is not supported, sorry for the         inconvenience",
           JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }          
}

最佳答案

您的代码有几个问题:

  1. provinceCode.ToUpper() 不会改变 provinceCode 的值。您需要为其分配 provinceCode = provinceCode.ToUpper()

  2. !justLetters.Equals(provinceCode) 正在检查 Regex 是否等于字符串 provinceCode。您需要使用 Regex.IsMatch() :

    if (!justLetters.IsMatch(provinceCode))
    
  3. 最后(感谢这里的 Carnivorus)您的 Regex 只查找一个大写字母。如果您更改正则表达式,则可以将前两个 if 语句合并为一个:

    var justLetters = new Regex("^[A-Z]{2}$");
    

正如对您的代码的一般小改进一样,您不需要在此处使用 elseif,因为无论如何您都在 if 语句中返回。

关于c# - 允许字符输入的正则表达式检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29011532/

相关文章:

c# - 是否应该在每个使用 MVC 的 View 中使用 ViewModel?

asp.net-mvc - MVC 4 中的主细节样式 View

javascript - ajax成功时调用c#方法

c# - 使用 Entity Framework 和 MVVM 将数据库信息从一个 ViewModel 传递到另一个

java - 查明 HTML 代码是否代表可见文本/图像

java - 结束行字符在 Java 正则表达式中不起作用

c# - 从对象转换为字符串时如何处理空异常?

c# - jQuery UI 自动完成组合框远程数据源

regex - PowerShell 条件效率 : -match vs. -like

asp.net-mvc - 在 MVC 中定义 html5 数据属性