6

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..?

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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/

1 Comment

I think that additionally to the change event you should also wire up the keyup event. Otherwise it's possible to manually enter a value which exceeds the max or is below the min and there is no correction or adjustment.
2

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">

2 Comments

I like your approach. showing the reverse value as validation.
Cannot input negative sign with keyboard first.
0
$(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);
    }
});

1 Comment

It would be helpful to explain what your code does with comments or additional commentary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.