Comment déclencher un validateur personnalisé côté client? C'est ce que j'ai jusqu'à présent:Validation côté client ASP.NET MVC de l'attribut personnalisé
Ma classe de validation:
public class AlmostEqual : ValidationAttribute, IClientValidatable
{
private readonly string _otherProperty;
private readonly float _myPercent;
public AlmostEqual(string otherProperty,float percent)
{
_otherProperty = otherProperty;
_myPercent = percent;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_otherProperty);
var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
dbEntities db = new dbEntities();
Metal metal = db.Metals.Find(Convert.ToInt32(otherPropertyValue));
double _unitWeight = metal.UnitWeight;
double _percent = metal.UnitWeight * (_myPercent/100);
double myProperty = double.Parse(value.ToString());
bool result = myProperty >= _unitWeight - _percent && myProperty <= _unitWeight + _percent;
if (!result)
{
return new ValidationResult(string.Format(
CultureInfo.CurrentCulture,
FormatErrorMessage(validationContext.DisplayName),
new[] { _otherProperty }
));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "almostequal",
};
rule.ValidationParameters.Add("other", _otherProperty);
yield return rule;
}
}
code de la classe METDATA:
[Required]
[AlmostEqual("IDMetal",5,ErrorMessage="Weight do not correspond with dimensions.")]
public Nullable<double> UnitWeight { get; set; }
}
Vu que je a ajouté js:
<script type="text/javascript">
$.validator.unobtrusive.adapters.addBool("almostequal", "Range");
</script>
Mon webconfig contient:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Je reçois l'erreur:
Uncaught TypeError: Impossible de lire la propriété 'appeler' undefined dans le fichier jquery.validate.min.js à la ligne 27
S'il vous plaît jeter un oeil à: http://stackoverflow.com/questions/4747184/perform-client-side-validation-for-custom-attribute/4747466 –
Le lien est de ce poste. – POIR
Désolé à ce sujet, mis à jour l'URL correcte –