skip to Main Content

How can enforce the required rule and if needed have an error display inside the SPAN tag?

Trying to add custom client side validation to a dotNET ASP MV* web page field Report.Name. For other reasons, I can’t add unobtrusive validation JQuery until a refactor is done. For now I’m trying to use JQuery validate. When I run a representation of the below code and submit with an empty field, I can get the fired events for showErrors and submitHandler. However, I’m not getting any invalid form errors. Methods this.valid() & this.numberOfInvalids() result in 0 as number of errors. The whole process just submits as if no errors exist.

Report.cshtml

<form method="post" id="formReport">
 . . .
<div class="form-group">
    <label asp-for="Report.Name" validation-for="Report.Name"></label>
    <input type="text" class="form-control" data-val-required="The Report Name field is required." asp-for="Report.Name" />
    <span asp-validation-for="Report.Name" class="text-danger"></span>
</div>
 . . .

Rendered HTML:

<input type="text" class="form-control" 
data-val-required="The Report Name field is required." 
data-val="true" 
data-val-maxlength="The field Report Name must be a string or array type with a maximum length of '35'." 
data-val-maxlength-max="35" 
id="Report_Name" 
maxlength="35" 
name="Report.Name" value="" />

JQuery:

$(document).ready(function () {
  $("#formReport").validate({
      submitHandler: function (form) {
          this.valid();
          var numOfErrors = this.numberOfInvalids();
          alert("submitHandler: " + numOfErrors);
          submitReport();
      },
      onsubmit: true,
      rules: {
        Report_Name: {
          required: true
        }
      },
      messages: {
        Report_Name: {
          required: "Testing: Report_Name required"
        }
      },
      showErrors: function (errorMap, errorList) {
          var numOfErrors = this.numberOfInvalids();
          alert("showErrors: " + numOfErrors);
      }
  });
}

2

Answers


  1. You must specify the exact name attribute of the <input> in the configuration. "." and "_" are not interchangeable. Since you have a name that isn’t a valid identifier, you need to quote it.

    rules: {
        "Report.Name": {
          required: true
        }
    },
    messages: {
        "Report.Name": {
          required: "Testing: Report_Name required"
        }
    },
    
    Login or Signup to reply.
  2. You can also consider using vanilla JavaScript. If the form should just submit to some URL you can leave out the last event listener (onsubmit).

    The oninvalid event listener (second) depend on the attribute required on the input element. When this attribute is set the input will validate based on the maxlength attribute and will also assume that the value is not an empty string.

    // Any input to any input in the form
    document.forms.form01.addEventListener('input', e => {
      // if some input, test if input is valid and if so
      // remove the class name 'invalid' being there or not
      if (e.target.validity.valid) {
        e.target.classList.remove('invalid');
      }
    });
    
    // If submit button if clicked or the function checkValidity()
    // on the form is called this eventlistener will trigger.
    // This overrides the default message by calling e.preventDefault();
    document.forms.form01.addEventListener('invalid', e => {
      e.preventDefault();
      // when something is invalid (input element being e.target)
      // set the class name 'invalid'
      e.target.classList.add('invalid');
    }, true);// notice the parameter 'true'
    
    // If form is valide and the form is submitting
    document.forms.form01.addEventListener('submit', e => {
      e.preventDefault();
      console.log('form submitting...');
    }, false);
    form {
      display: flex;
      flex-direction: column;
    }
    
    input~span {
      display: none;
      background-color: orange;
    }
    
    input.invalid~span {
      display: inline;
    }
    <form name="form01">
      <label>
        <span>Report name:</span>
        <input type="text" class="form-control"
          data-val-required="The Report Name field is required." 
          data-val="true" 
          data-val-maxlength="The field Report Name must be a string or array type with a maximum length of &#x27;35&#x27;." 
          data-val-maxlength-max="35"  
          maxlength="35" 
          name="Report.Name"
          required/>
        <span class="text-danger">The field Report Name must be a string or array type with a maximum length of &#x27;35&#x27;.</span>
      </label>
      <label>
        <button type="submit">Submit</button>
      </label>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search