Reputation: 113
For Example:
Rule(x=x.Password)
.Matches(@"(**?:[^˜!@#$]*[˜!@#$]**){" + count+ "}")
.WithMessage("Password should contain at least {0} special character(s)", count);
Here in above not matches all special characters like dot,plus+ etc.
Upvotes: 2
Views: 5145
Reputation: 728
Declare regex variable like below line.
readonly Regex regEx = new Regex("^[a-zA-Z0-9]*$");
Refer below code for usage.
RuleFor(x=x.Password).Cascade(CascadeMode.StopOnFirstFailure)
.Matches(regEx)
.WithMessage("Password should contain at least {0} special character(s)", "Password"));
Upvotes: 6
Reputation: 57
I don't know how to use a single regex to do this. But you can use custom validator for your validation.
class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.Name).SetValidator(new PasswordValidator());
}
}
class PasswordValidator : PropertyValidator
{
private const int Count = 3;
private readonly Regex regex;
const string expression = @"[^A-Za-z0-9]";
public PasswordValidator()
: base(() => "Property {PropertyName} is not in the correct format.")
{
regex = new Regex(expression, RegexOptions.IgnoreCase);
}
protected override bool IsValid(PropertyValidatorContext context)
{
if (context.PropertyValue == null) return false;
var collection = regex.Matches((string)context.PropertyValue);
return collection.Count >= Count;
}
}
Upvotes: 1