Client-side validation fails for RequiredIf

I am using ExpressiveAnnotations from JaroslawWaliszko . It works great when I check the server side through ModelState.IsValid. But it does not show a validation message on the client side. I don’t know what is missing. I also added a jquery file. Here is the property I applied to RequiredIf:

// When Role = Assistant Professor(which has id = 3), 
// His/ Her head Id should be selected as ParentID.

[RequiredIf("RoleID == 3", ErrorMessage = "Select Head.")] 
public Nullable<int> ParentID { get; set; }

The HTML presented is as follows:

<select class="form-control ng-pristine ng-valid" 
        data-val="true" 
        data-val-number="The field ParentID must be a number." 
        data-val-requiredif="Select Head." 
        data-val-requiredif-allowempty="false" 
        data-val-requiredif-constsmap="{}" 
        data-val-requiredif-expression="RoleID == 3" 
        data-val-requiredif-fieldsmap="{"RoleID":"numeric"}" 
        id="ParentID" 
        name="ParentID" 
        ng-model="DTO.ParentID" 
        ng-options="obj.Value as obj.Text for obj in headList">

    <option selected="selected" value="" class="">--select--</option>
    <option value="0">Mr. Kevin Thomas</option>
    <option value="1">Ms. Lisa Brown</option>
    <option value="2">Mr. Sail Kapoor</option>
</select>

Things I implemented:

  • Installed Package: Install-Package ExpressiveAnnotations,
  • Added code below in Global.asax

    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof (RequiredIfAttribute), typeof (RequiredIfValidator));
    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof (AssertThatAttribute), typeof (AssertThatValidator));
    
  • Added expressive.annotations.validate.js to the package below jquery validation files and added the package on the specified page.

+4
1

. ?

, :

public class Model
{
    public IEnumerable<SelectListItem> Supervisors
    {
        get
        {
            return new[]
            {
                new SelectListItem {Text = "Mr. Kevin Thomas", Value = "0"},
                new SelectListItem {Text = "Ms. Lisa Brown", Value = "1"},
                new SelectListItem {Text = "Mr. Sail Kapoor", Value = "2"}
            };
        }
    }

    [RequiredIf("RoleID == 3", ErrorMessage = "Select Head.")]
    public int? ParentID { get; set; }
    ...

:

@Html.DropDownListFor(model => model.ParentID, Model.Supervisors, "--select--")
@Html.ValidationMessageFor(model => model.ParentID)

, , , .

UPDATE:

.

+2

Source: https://habr.com/ru/post/1568093/


All Articles