Home > Software engineering >  How to validate both input text
How to validate both input text

Time:09-30

I want to show the message "Input Number Only" if I oninput the alphabet. The first text box is successfully show but when I input alphabet into the second text box it does not show anything at the span. How to edit my code so that it will show the message after I on input the alphabet. Here my code :

function allvalidate(){
    var inp = document.getElementsByClassName('text');
    for(var i in inp){
    if(inp[i].type == "text"){
        if(!/^\d{1,}$/.test(inp[i].value)){
            error.textContent = "Input Number Only";
            error.style.color = "red";

            return false;
            }
        else {
            error.textContent = "";
            }
        return true;
            break;
        }
    }
}
<p>Number of Customer</p>
                <p><input type="text" name="people"  placeholder="no.of people" size="18" maxlength="10" oninput="allvalidate()"></p>
                <p>Age</p>
                <p><input type="text" name="post"  placeholder="postcode" size="18" maxlength="2" oninput="allvalidate()"></p>
                <span id="error"></span>

CodePudding user response:

Replace the following statement:

for(var i in inp){

with

for(let i=0 ;i<inp.length;i  ){

CodePudding user response:

A delegated event listener bound to the document can intercept and process all the input elements without needing to explicitly add the oninput event handler to each one as above. That event handler can likely also be simplified by using isNaN rather than a regex

const errspan=document.getElementById('error');

document.addEventListener('input',e=>{
  error.textContent = "";  
  if( e.target.type=='text' && isNaN( e.target.value ) ) {
    error.textContent = "Input Number Only";
  }
})
#error{
  color:red
}
<p>Number of Customer</p>
<p>
  <input type="text" name="people"  placeholder="no.of people" size="18" maxlength="10" />
</p>

<p>Age</p>
<p>
  <input type="text" name="post"  placeholder="postcode" size="18" maxlength="2" />
</p>


<span id="error"></span>

  • Related