0

I have a textarea which i want to set it to required. I'm trying to use the rulefor from the fluentvalidation but still not happening something.

i have try also too to use the [required] etc. Someone can give me a hand with this?

Here is my code:

Model:

public class MainValidator : AbstractValidator<Main>
{
    public MainValidator()
    {
        RuleFor(x => x.Message).NotEmpty().WithMessage("Required field");
    }
}

View:

<textarea id="message" name="message"></textarea>
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user2232273
  • 4,898
  • 15
  • 49
  • 75

2 Answers2

1

Try the following. Serverside:

RuleFor(x => x.Message).NotNull().WithMessage("Required field");

I could not find that easyli as I thought sources of RuleFor method, so you can just try this:

RuleFor(x => x.Message).NotEmpty().NotNull().WithMessage("Required field");

Also, the clientside:

<textarea required id="message" name="message"></textarea>
AgentFire
  • 8,944
  • 8
  • 43
  • 90
0

I'm using FluentValidation.AspNetCore 8.1.3

I had same problem and I resolved this way:

Validator

public ContactValidator(){ 
    RuleFor(x => x.Message).NotEmpty().WithMessage("Message Required").Length(10, 400).WithMessage("Message must be between 10 and 400 characters");
}

Model

public class ContactViewModel
{
    [DataType(DataType.MultilineText)]//<-- Add this line to work
    public string Message { get; set; }
}

View

<div class="col-md-12 col-sm-12">
<textarea asp-for="Message" name="Message" class="form-control" placeholder="Message"></textarea>
<span asp-validation-for="Message" class="text-danger"></span>
</div>

Fabio
  • 141
  • 4
  • 13