Mr world wide
Mr world wide

Reputation: 4844

validation for input type number with minimum and maximum range

I want to validate if the input type number crosses the range.

<input type="number" min="-10" max="10"  required="true" message="you can give score -10 to +10 only">

I tried required = true but not working i want to show if the value crosses the range show message like you can give score -10 to +10 only

I want to allow while entering itself, not when submitting.

How can i do that..?

Upvotes: 6

Views: 52590

Answers (4)

konstantin k
konstantin k

Reputation: 1

$(document).on('change', 'input', function() {
    var max = parseFloat($(this).attr('max'));
    var min = parseFloat($(this).attr('min'));
    if (parseFloat($(this).val()) > max) {
        $(this).val(max);
    } else if (parseFloat($(this).val()) < min) {
        $(this).val(min);
    }
});

Upvotes: 0

Abdullah Arık
Abdullah Arık

Reputation: 21

This is the vanilla js way.

document.querySelector('input').addEventListener('input', e=>{
  const el = e.target || e

  if(el.type == "number" && el.max && el.min ){
    let value = parseInt(el.value)
    el.value = value // for 000 like input cleanup to 0
    let max = parseInt(el.max)
    let min = parseInt(el.min)
    if ( value > max ) el.value = el.max
    if ( value < min ) el.value = el.min
  }
});
<input type="number" min="-10" max="10"  required="true" title="you can give score -10 to +10 only">

Upvotes: 2

Ankit Agarwal
Ankit Agarwal

Reputation: 30729

You can look at this jsfiddle i have created. https://jsfiddle.net/6bkws7zd/

HTML

<input id="txtNumber" type="number" message="you can give score -10 to +10 only" />
<span id="errorMsg" style="display:none;">you can give score -10 to +10 only</span>

Jquery

$("#txtNumber" ).keyup(function() {
  if($('#txtNumber').val()<-10 || $('#txtNumber').val()>10 ){
      $('#errorMsg').show();
  }
  else{
    $('#errorMsg').hide();
  }
});

You can add required field to input control if you want to make it required.

Upvotes: 7

Katie
Katie

Reputation: 48308

Instead of hard coding "10" and "-10" in your function, you can get the min and max values from the element and check if it's within range.

$(function () {
   $( "input" ).change(function() {
   var max = parseInt($(this).attr('max'));
   var min = parseInt($(this).attr('min'));
   if ($(this).val() > max)
   {
      $(this).val(max);
   }
   else if ($(this).val() < min)
   {
      $(this).val(min);
   }       
 }); 
});

@Caspian also provided a working fiddle: http://jsfiddle.net/Ddk67/75/

Upvotes: 5

Related Questions