kodder360
kodder360

Reputation: 99

How to allow one specific word into text field in form using javascript?

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>

Upvotes: 1

Views: 1025

Answers (2)

imvain2
imvain2

Reputation: 15857

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>

Upvotes: 3

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

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>

Upvotes: 0

Related Questions