Pregunta

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>
¿Fue útil?

Solución

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>

Otros consejos

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>

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top