-1

I want to write a code for not allowing to take special character or whitespace as input.

eg:- TN03UB8192

this is the required input. If i input as: TN03U* it woun=ld not take * as input. Instead of taking it as input need to halt or take next allowed character as input.

Now i have a code this is working but will show alert only after 10 key press. Please help me

function alphanumeric(inputtxt)  
    {   
        var letters = /[A-Z]{2}[0-9]{2}[A-Z]{2}[0-9]{4}$/;  
        if(inputtxt.value.match(letters))  
            {  
                alert('Your registration number have accepted : you can try another');  
                document.form1.text1.focus();  
                return true;  
    }  
    else  
    {  
        alert('Please input in correct format');  
        return false;  
    }  

}

cse project
  • 53
  • 1
  • 8
  • : function alphanumeric(inputtxt) { var letters = /[A-Z]{2}[0-9]{2}[A-Z]{2}[0-9]{4}$/; if(inputtxt.value.match(letters)) { alert('Your registration number have accepted : you can try another'); document.form1.text1.focus(); return true; } else { alert('Please input in correct format'); return false; } } Now iam using this code – cse project Mar 16 '17 at 08:55

1 Answers1

0

You'll definitely want to have both client side and server-side checking for this. You want it on the client side just to avoid the hassle of submitting the form and then it coming back saying the input is wrong.

Here is a link to a question that was asking a similar thing. Be sure to read all the answers, because there are fringe cases, like pasting, where you want to apply the filter as well, not just with individual keypress checks.

Stealing one of the non-accepted answers, because its better than the accepted one for our purposes.

var text = document.getElementById('text');
text.onkeypress = text.onpaste = checkInput;

function checkInput(e) {
  var e = e || event;
  var char = e.type == 'keypress' 
    ? String.fromCharCode(e.keyCode || e.which) 
    : (e.clipboardData || window.clipboardData).getData('Text');
  if (/[^\d]/gi.test(char)) {
    return false;
  }
}

If the event is a keypress, var char will become the letter of the key they pressed. if the event is not a keypress, then it must be a paste, so char = clipboard data. next, we run the regex check to see if the data passes. if not, we return false (don't let that new text be entered into the input box). If it does pass, don't do anything, just let the input act as it normally would, accepting the valid thing you just entered into it.

Community
  • 1
  • 1
Bango
  • 971
  • 6
  • 18