Solution 1 :

Here is my javascript solution: It uses a single If statement to check if the string is a number or ALL. Technically you don’t need the isNaN function in there so if you want to remove it, the if statement will still work.

var _input = document.querySelector(".validate-num");
var _min= 1000;
var _max = 10000;

_input.addEventListener("input",function(){
   var _valid = ((isNaN(this.value) && this.value.toLowerCase() == "all") || (!isNaN(this.value) && (this.value >= _min && this.value <= _max)));

if(!_valid){
var error = document.getElementById("error");
 error.innerHTML = "Value Must be 1000 to 10000 or ALL";
}
});
<input type="text" class="validate-num form-control" id="validationCustom02" required>

Solution 2 :

A number type can’t have strings into it, you will have to have a text input with an Event listener which does the validation job For You. Here, I have added a blur listener, it would trigger once you move away from the input.

const inputElem = document.querySelector('#validationCustom02required');
inputElem.addEventListener('blur', (e) => {
  const val = e.target.value;
  let showError = false;
  if (isNaN(val)) {
    if (val.toLowerCase() !== 'all') {
      showError = true;
    }
  } else {
    const numVal = +val;
    if (val < 1000 || val > 10000) {
      showError = true;
    }
  }
  
  const errorElem = document.querySelector('#error');
    if (showError) {
      errorElem.innerText = 'Invalid; Value!';
    } else {
      errorElem.innerText = '';
    }
})
<input type="text" class="form-control" id="validationCustom02required">
<div id="error"></div>

Problem :

I have input number field which is from 1000 to 10000 range but I also want to allow one only word ‘All’ into this field if user enter any word then show error. I have not written any JavaScript code for this because I do not have any idea how to do this. can anyone help me out please? Thanks

<input type="text" class="form-control" id="validationCustom02" min="1000" max="10000" required>

Comments

Comment posted by Pointy

You cannot do that. A

Comment posted by kodder360

I am going to edit my my question from number to text. can u please tell me how to allow numbers from min=1000 to max=10000 numbers with only one word all?

Comment posted by nemo

What about instead having a checkmark next to the input field for “all” and it disables the input field? That feels like a more intuitive UX to me.

Comment posted by kodder360

thanks for your answer. How to display error on page?

Comment posted by kodder360

Instead of console I just want to show error on page. I tried but not working.

Comment posted by kodder360

var error = document.getElementById(“error”); and i put error.innerHTML = ” Value Must be 1000 to 10000 or ALL”; inside addEventListerner..

By

Leave a Reply

Your email address will not be published. Required fields are marked *