How to use custom validation in grid

I have used grid in my application.

I would like to know how to use custom validation in batch mode.

For example in my grid there are two column

Stock Qty : 1000
Issued Qty : 1005

If issued qty is greater than stock quantity in grid cell then it should validate (Issued qty should not greater than stock quantity)

3 Replies 1 reply marked as answer

RS Renjith Singh Rajendran Syncfusion Team April 13, 2021 12:04 PM UTC

Hi Ismail, 

Greetings from Syncfusion support. 

We can achieve this requirement by using DataAnnotation. Please refer and use as like the below codes to achieve custom validation for the IssueQty column based on StockQty. We are also attaching a sample for your convenience, please download the sample from the link below, 

 
public class Order 
{ 
    public int? OrderID { getset; } 
    public string CustomerID { getset; } 
    public DateTime? OrderDate { getset; } 
    public int StockQty { getset; } 
    [IssueQtyValidation] 
    public int IssueQty { getset; } 
    public string ShipCountry { getset; } 
} 
public static bool ValidFlag; 
 
[AttributeUsage(AttributeTargets.Property)] 
public class IssueQtyValidationAttribute : ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
        // Here you can perform your custom validation and return true/false value 
        var ContextValue = (Order)validationContext.ObjectInstance; 
        if (Int32.Parse(value.ToString()) > ContextValue.StockQty) 
        { 
            ValidFlag = true; 
        } 
        else 
            ValidFlag = false; 
        return ValidFlag ? new ValidationResult("Enter Proper value"new[] { validationContext.MemberName }) : ValidationResult.Success; 
    } 
} 


Please get back to us if you need further assistance. 

Regards, 
Renjith R 


Marked as answer

MT Martin Tirion January 25, 2023 02:38 PM UTC

I have an additional question on this topic. I have a setup like described above. But I have a validator that depends on another field. In this sample the freight can be 0 if the shipcity is "Munster".

In Normal mode, changing an entry with shipcity not in Munster throws the error on entering 0 in freight. In I change a line with shipCity = Munster to freight=0 it's okay. If I then change the shipCity to "lyon" the validation on freight fails - that's what I want.

In batch mode setting freight to 0 for shipCity "Lyon" shows the validation error. But if I change freight to 0 on an entry with Munster and then change the shipCity to "Lyon" the validation error is NOT shown. 

How should this be done?

The sample:

@page "/"


<PageTitle>Test DataGrid</PageTitle>


@using Syncfusion.Blazor.Grids;

@using System.ComponentModel.DataAnnotations;

@using System.Text.RegularExpressions;


<SfGrid DataSource="EmployeeList" AllowPaging="true" Toolbar="toolbar">

    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"

        Mode="Syncfusion.Blazor.Grids.EditMode.Batch"></GridEditSettings>

    <GridColumns>

        <GridColumn Field="@nameof(EmployeeDetails.OrderID)"

        HeaderText="Order ID" TextAlign="TextAlign.Right" IsPrimaryKey="true" > </GridColumn>

        <GridColumn Field="@nameof(EmployeeDetails.CustomerName)"

        HeaderText="Customer Name" TextAlign="TextAlign.Left"> </GridColumn>

        <GridColumn Field="@nameof(EmployeeDetails.EmployeeID)"

        HeaderText="Employee ID" TextAlign="TextAlign.Right"> </GridColumn>

        <GridColumn Field="@nameof(EmployeeDetails.Freight)"

        HeaderText="Freight" TextAlign="TextAlign.Right" Format="C2"> </GridColumn>

        <GridColumn Field="@nameof(EmployeeDetails.ShipCity)"

        HeaderText="Ship City" TextAlign="TextAlign.Left"> </GridColumn>

        <GridColumn Field="@nameof(EmployeeDetails.ShipName)"

        HeaderText="Ship Name" TextAlign="TextAlign.Left"> </GridColumn>

    </GridColumns>

</SfGrid>


@code

{

    List<EmployeeDetails> EmployeeList;

    string[] toolbar = new string[] { "Add", "Edit", "Delete", "Update", "Cancel" };

    protected override void OnInitialized()

    {

        base.OnInitialized();

        EmployeeList = Enumerable.Range(1, 20).Select(x => new EmployeeDetails()

            {

                OrderID = 10240 + x,

                CustomerName = new string[] { "VINET", "TOSMP", "HANAR", "VICTE" }[new Random().Next(4)],

                EmployeeID = x,

                Freight = new float[] { 32.28f, 22.90f, 30.99f, 50.52f }[new Random().Next(4)],

                ShipCity = new string[] { "Reims", "Munster", "Rio de Janeir", "Lyon" }[new Random().Next(4)],

                ShipName = new string[] { "Vins et alocools chevalie", "Toms Spezialitaten", "Hanari Carnes", "Supremes delices" }[new Random().Next(4)]

            }).ToList();

    }

    public class EmployeeDetails

    {

        [Required]

        public int? OrderID { get; set; }

        public string CustomerName { get; set; }

        [CustomValidationEmployeeID]

        public int EmployeeID { get; set; }

        [CustomValidationFreight]

        public float Freight { get; set; }

        public string ShipCity { get; set; }

        public string ShipName { get; set; }

    }

    public class CustomValidationEmployeeID : ValidationAttribute

    {

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)

        {

            if (value != null)

            {

                int employeeID = Convert.ToInt16(value);

                if (employeeID >= 1)

                {

                    return ValidationResult.Success;

                }

                else

                {

                    return new ValidationResult("Employee ID value should be greater than zero");

                }

            }

            else

            {

                return new ValidationResult("Employee ID value is required");

            }

        }

    }

    public class CustomValidationFreight : ValidationAttribute

    {

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)

        {

            if (value != null)

            {

                float freight = (float)value;

                if (freight >= 1 && freight <= 10000 || ((EmployeeDetails)validationContext.ObjectInstance).ShipCity == "Munster")

                {

                    return ValidationResult.Success;

                }

                else

                {

                    return new ValidationResult("Freight value should between 1 and 10,000");

                }

            }

            else

            {

                return new ValidationResult("Freight value is required");

            }

        }

    }

}



MS Monisha Saravanan Syncfusion Team January 26, 2023 10:43 AM UTC

Hi Martin,


Greetings from Syncfusion.


We have reviewed your query and have been able to reproduce the reported issue when using the code snippet you provided. We understand that you would like to display validation messages on other fields based on certain conditions while in batch editing mode. However, we would like to inform you that validation messages are only displayed when the form is in an edited state. Therefore, it is not currently possible to display validation messages on other fields in batch editing mode.


Instead we suggest you to create a Custom validation for the ShipCity column to prevent entering ship city other than Munster when the freight value is zero.


Please let us know if you have any concerns.


Regards,

Monisha


Loader.
Up arrow icon