Make regular expression case insensitive in ASP.NET RegularExpressionValidator

后端 未结 5 1999
暗喜
暗喜 2020-11-27 19:40

Given this regular expression: \"^[0-9]*\\s*(lbs|kg|kgs)$\" how do I make it case insensitive? I am trying to use this in a .net regular expression validator,

5条回答
  •  时光取名叫无心
    2020-11-27 20:06

    Here is an alternative using a CustomValidator, when really needing case-insensitivity server-side and client-side; and the the Upper/lower [A-Za-z] char approach is too much.

    This blends the various other answers, using the server-side RegEx object and client-side JavaScript syntax.

    CustomValidator:

    
    

    Code behind:

    protected void cvWeight_Validate(object sender, ServerValidateEventArgs args)
    {
        Regex re = new Regex(@"^[0-9]*\s*(lbs|kg|kgs)$", RegexOptions.IgnoreCase);
        args.IsValid = re.IsMatch(args.Value);
    }
    

    Client-side validation function:

    function cvWeight_Validate(sender, args) {
      var reWeight = /^[0-9]*\s*(lbs|kg|kgs)$/i;
      args.IsValid = reWeight.test(args);
    }
    

    This is working fine for me, except when using a ValidationSummary. On the client-side validation, the error * shows, but I can't get the error message to display in the summary. The summary only displays when submitted. I think it's supposed to display; I have a mix of update panels and legacy code, which may be problems.

提交回复
热议问题