Home > database >  ASP.NET MVC: Custom Validation by DataAnnotation base on two fields length
ASP.NET MVC: Custom Validation by DataAnnotation base on two fields length

Time:08-05

I have this JS method that I am using to do some validation. But I wanted to see if I can build a Custom Validation by DataAnnotation. Is there a way for me to collect this information so I can use it in a custom validation? And will this do JS validation?

JS code I want to replace

function materialsconfirmhasError() {
    let materialsconfirm = $('input[name="ckmaterialsconfirm"]:checked').length > 0;
    let uploadcontrol = $("#upImport").data("kendoUpload"),
        files = uploadcontrol.getFiles();

    let FileLink = $("#txtFileLink").val();
    console.log(FileLink);
    if (files.length !== 0 || FileLink.length !== 0) {
        if (materialsconfirm == false) {
            $("#lblConfirmError").show();
            return true
        } else {
            $("#lblConfirmError").hide();
            return false
        }
    }
    return false
}

HTML

<div id="materialsconfirm" >
    <div >
        <div >
            @Html.CheckBoxFor(x => x.materialsconfirm,new { id= "ckmaterialsconfirm", @class= "form-control" })
            @*<label for="ckmaterialsconfirm"> I have read and adhered to the above statements</label>*@
        </div>
    </div>
    <div >
        <div >
            <label id="lblConfirmError"  style="display:none">Please Confirm.</label>
        </div>
    </div>
</div>

Model

[Display(Name = "I have read and adhered to the above statements")]
[CustomMaterialValidator]
public Boolean materialsconfirm { get; set; }

CustomMaterialValidator

 public class CustomMaterialValidator: ValidationAttribute {
     protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
         if (value != null) {
             bool flgCustomMaterial = value is bool ? (bool) value : false;

             if (flgCustomMaterial == true) {
                 return ValidationResult.Success;
             } else {

             }

             return new ValidationResult("Please Confirm.");
         }
         return new ValidationResult("Please Confirm.");
     }

 }

CodePudding user response:

You can write a custom ValidationAttribute that reads other properties from your model. You can do so using the ValidationContext available to you in your overload of the IsValid method.

You can access a different property this way:

    var otherPropertyInfo = validationContext.ObjectType.GetProperty("OtherPropertyName");
    if (otherPropertyInfo == null) {
        return new ValidationResult("The other property doesn't exist");
    }

    object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);

In this example, the value will be in otherPropertyValue and you can implement the validations you need using this value along with the value of your annotated property (materialsconfirm in your case).

You can make this attribute work on the client side by signaling from your ValidationAttribute that it has client side validation and creating a jQuery validator for it, as illustrated here, but that will require you to translate your validation logic into JS.

If you want these validations to happen on the client side using server-side logic, you can implement the [Remote] attribute which lets you specify an action that will be called to validate the property. You can also specify additional properties that will be used to perform the validation. You can find some examples on how to implement this option including additional properties here. The downside is that this validation is not enforced on the server.

  • Related