Reputation: 177
I am using custom validation within Blazor, the validation is performed correctly, however when it is not valid the ValidationMessage For is not displayed, I tried adding ValidationSummary and here it does appear ErrorMessage. I hope someone can support me
public class Domicilio
{
public int Id { get; set; }
public DateTimeOffset FechaRegistro { get; set; }
[Required(ErrorMessage ="Favor de capturar la calle")]
public string Calle { get; set; }
[Required(ErrorMessage = "Favor de capturar el número exterior")]
public string NumeroExt { get; set; }
public string NumeroInt { get; set; }
[Range(1,int.MaxValue, ErrorMessage="Favor de seleccionar la colonia")]
public int CodigoPostalId { get; set; }
public CatCodigosPostales CodigoPostal { get; set; }
[OtroCPValidation]
public string OtroCodigoPostal { get; set; }
public string OtraColonia { get; set; }
public string OtraCiudad { get; set; }
public string OtroEstado { get; set; }
[Range(1,int.MaxValue,ErrorMessage="Favor seleccione el país")]
public int PaisId { get; set; }
public CatPaises Pais { get; set; }
public string Observaciones { get; set; }
}
public class OtroCPValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var domicilio = (Domicilio)validationContext.ObjectInstance;
if (domicilio.Pais.Pais != "México" && domicilio.OtroCodigoPostal == null)
{
return new ValidationResult($"Captura el código postal extranjero");
}
else
return ValidationResult.Success;
}
}
<EditForm Model="Domicilio" OnValidSubmit="OnValidSubmit" style="height:75vh" class="row justify-content-center align-items-center">
<DataAnnotationsValidator />
<div class="form-group">
<label>Código postal</label>
<div>
<SfMaskedTextBox Placeholder="Código postal" Mask="[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" @bind-Value="@Domicilio.OtroCodigoPostal"></SfMaskedTextBox>
<ValidationMessage For="@(() => Domicilio.OtroCodigoPostal)" />
</div>
</div>
</EditForm>
Upvotes: 3
Views: 3043
Reputation: 177
I was able to solve the problem I had, I was missing an overload in the return of the IsValid method, I leave the return as it should be, I just needed that change.
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName});
Upvotes: 13
Reputation: 30485
Two things to check:
using System.ComponentModel.DataAnnotations;
namespace StackOverflow.Answers
{
public class AlwaysInvalidValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return new ValidationResult($"Error Message");
}
}
}
Test with the basic Blazor Input
controls.
Refactor the logic so you return an error unless the value passes the logic test.
I've tested a version of your code and it works.
Upvotes: 0