简体   繁体   中英

Regular Expression in MVC of c# to match characters

I am using a regular expression to match some characters like ç"·$%&/()=? , etc.

I am testing the regular expression in the web page

http://www.softlion.com/webTools/RegExpTest/default.aspx

and it is working but when I use the regular expression in my model of MVC it is not working and always I display the message of error.

The instruction used in c# is:

[RegularExpression(@"[ç\"·$%&/()=?]$", ErrorMessage="some message")]

ç\\"·$%&/()=?]$ are disallowed characters

I still have the problem, and I don't understand why it is not working

I always see the error message if I write something like: ABCDEF (for me it is the right characters) or ABCDçEF=GHIJ (incorrect)

In the model I changed RegularExpression like a Custom Attribute. In the property of the model I have:

[CaracteresNoPermitidosAttribute(ErrorMessage="test 123")] public string RazonSocial { get; set; }

And the Attribute class is:

public class CaracteresNoPermitidosAttribute : RegularExpressionAttribute
{
public CaracteresNoPermitidosAttribute() : base(GetRegex())
{ }

private static string GetRegex()
{
// I take the data from the table to get the disallowed characters
var lista = (List<Caracterko>) new CaracterkoProxy().ObtenerTodos();

// I transform the list to string
var str = string.Join("", from x in lista where x.Activo select x.Caracter.ToString());

return @"(?![" + str + "])$";
}
}

I used the example gave by Tim as regular expression

Your regular expression is only looking for one character and then the end of the string. If you only want to allow characters in that set, you should use an expression like - [ç\\"·$%&/()=?]+$

Since you clarified that you do NOT want these characters in your string, use a negative lookahead:

(?![ç\\"·$%&/()=?])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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