Search code examples
htmlcheckvalidity

Html: JavaScript: input: razor:minRange and maxRange


I have an input element with a minRange and maxRange set and am trying to get a custom validity message. I also have a Input TagHelper to write a custom message that I am trying to override on client-side. I have tried this so far and it doesn't seem to be working.

<input asp-for="Amount" minRange="50.00" maxRange="100.00" oninput="check(this)" />



<script type="text/javascript">
  function check(input) {
    if (input.validity.rangeUnderflow || input.validity.rangeOverflow) {
      input.setCustomValidity("Please enter an amount between $50.00 and $100.00.");
    }

  }
</script>

Rendered html:

<input oninput="check(this)" type="text" data-val="true" data-val-number="The field Amount must be a number." data-val-required="The Amount field is required." id="Model_Amount" name="Model.Amount" value="97.95" data-val-range-min="50.00" data-val-range-max="100.00" data-val-range="Please enter an Amount between 50.00 and 100.00" class="form-control valid" placeholder="Amount" aria-required="true" aria-invalid="false" aria-describedby="Model_Amount-error">

It still inputs "Please enter Amount between 50.00 and 100.00"

input taghelper:

    public override void Process(TagHelperContext context, TagHelperOutput output)
        {
          if (MinRange != null && MaxRange != null)
            {                    
                TagHelperAttribute minAttr = new TagHelperAttribute("data-val-range-min", MinRange);
                output.Attributes.Add(minAttr);
                TagHelperAttribute maxAttr = new TagHelperAttribute("data-val-range-max", MaxRange);
                output.Attributes.Add(maxAttr);
                TagHelperAttribute rangeAttr = new TagHelperAttribute("data-val-range", string.Format("Please enter a {0} between {1} and {2}", DisplayName, MinRange, MaxRange));
                output.Attributes.Add(rangeAttr);
            }
    }

Any help is appreciated. Thanks NH


Solution

  • Changed your code with some comments added. Hope this helps

    <!DOCTYPE html>
    <html>
    <head>
    <title>Test</title>
    </head>
    <body>
    
    <!-- Change minRange/maxRange to just min/max -->
    <input asp-for="Amount" min="50.00" max="100.00" oninput="check(this)" />
    
    <span id="display"></span>
    
    </body>
    <script type="text/javascript">
    
    function check(input) {
        //Get current input field value
        var num = parseInt(document.querySelector('input').value);
    
        //Check if num is < or > than input.min/max
        if(num >= input.min && num <= input.max){
            document.getElementById('display').innerText = '';
        }else{
            document.getElementById('display').innerText = 'Number must be between 50 and 100';
        }
    }
    
        
    </script>
    </html>