praval
praval

Reputation: 206

Regex is not working in c# but working in javascript

I am trying to validate string should not start with some character and should not contain <>.

[Required]
[Display(Name = "First name")]
[MaxLength(50)]
[RegularExpression(@"(?=(^(?!.*[><]).*$))(?=(^(?![@\+\-=\*]).*))", ErrorMessage = "firstname"+ Constants.DisplayMessage)]
public string firstname { get; set; }

this regex is working in javascript. but it is not working in c#. I have already spent almost 1 hours on it but no result please help me. ya also tried using (^(?!.*[><]).*$)|(^(?![@\+\-=\*]).*) this regex.but it is not working. I am not good at regex so please help me.

Upvotes: 0

Views: 685

Answers (2)

JyothiJ
JyothiJ

Reputation: 315

Having proper set validator, it works in C# too public class NameProp { string m_firstname;

    [Required]
    [Display(Name = "First name")]
    [MaxLength(50)]
    [RegularExpression(@"^(?![@=*-])(?!.*[<>]).*$", ErrorMessage = "firstname contains <> or start with @=*-")]
    public string firstname
    {
        get { return m_firstname; }

        set
        {
            Validator.ValidateProperty(value,
                new ValidationContext(this, null, null) { MemberName = "firstname" });
            m_firstname = value;
        }
    }

}

public class Program {

    static void Main(string[] args)
    {
        NameProp np = new NameProp();
        try
        {
            np.firstname = "<>JJ";
        }
        catch (ValidationException ex)
        {
            Console.WriteLine(ex.Message);
        }

    }
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522396

Based on your description what the regex needs to do, the following pattern should work:

^(?![@=*-])(?!.*[<>]).*$

Explanation:

^
(?![@=*-])    from the start of string, assert that @=*- is not the first character
(?!.*[<>])    also assert that <> does not appear anywhere in the string
.*            then match anything (our assertions having be proven true)
$

Demo

This pattern is also working for C#, as you can see by exploring the second demo below.

C# Demo

Upvotes: 2

Related Questions