26

I just need to allow a user to enter the following characters in the textinput:

a-zA-Z0-9!@#$%^*_|

<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
  User Name:<br />
  <input type="text" name="userName" size="25" /><br />
  Password:<br />
  <input type="password" name="pw" size="25" /><br />
  <input type="submit" value="Log In" onClick="validate()"/> 
</form>

Above is my HTML, and Below is my JavaScript I tried to use to validate it - but it doesnt work - any clues.

<script language="javascript">
   document.logOn.onsubmit=validate;

   function validate(){

var name=document.logOn.pw.value;
    if(!name = "[a-zA-Z0-9!@#$%^*_|]"){              
alert("Your Password Cant Have any thing other than a-zA-Z0-9!@#$%^*_| - Play It Straight!");
    return false;
}               

    return true;
}

</script>

But This isnt working. I can still put chars in like ">" and "<" and "{" etc.

Any Thoughts?

baburao113
  • 785
  • 2
  • 8
  • 12
  • where exactly you are getting stuck? – Anuj May 08 '13 at 06:40
  • I want to allow a user to enter only these characters: a-zA-Z0-9!@#$%^*_| to enter in a password field. I don't want him to enter other than these characters – baburao113 May 08 '13 at 06:43
  • Possible duplicate of [HTML5 restricting input characters](https://stackoverflow.com/questions/13607278/html5-restricting-input-characters) – Jo Liss Feb 25 '19 at 15:14
  • Article https://www.linkedin.com/pulse/javascript-dom-allow-enter-particular-characters-only-aniket-jha/ – Aniket Jha May 09 '20 at 13:57

6 Answers6

47

You can change your input text as below:

<input type="text" pattern="[a-zA-Z0-9!@#$%^*_|]{6,25}" />

So the code changes look like below:

    <form action="#" method="get">
       User Name:<br />
       <input type="text" pattern="[a-zA-Z0-9!@#$%^*_|]{6,25}" /><br />
       Password:<br />
       <input type="password" /><br />
       <input type="submit" value="Log In" /> 
   </form>

This will work without using JavaScript. pattern can be used instead. It is more effective than JavaScript for form validation.

Community
  • 1
  • 1
Ankit Dhadse
  • 1,566
  • 1
  • 15
  • 19
  • 9
    nope.. I'm still able to put '>' '<' '{' '}' in the text field :( – baburao113 May 08 '13 at 07:04
  • i have a question,how does this do `alert` or other event – 5z- - May 08 '13 at 07:06
  • 1
    @baburao113: yes, i know u are able to type it. but when you click on Login button then it inputtext will notify that the specified value is incorrect. and will request user to please match the required format. try it. it will work. it works fine for me. – Ankit Dhadse May 08 '13 at 07:10
  • 2
    @bull-T when user click on Login button then the input text will not notify you as `"please match the requested format"` hope you got understood the method. try it. it will work. – Ankit Dhadse May 08 '13 at 07:12
  • But if a user(hacker) changes/removes the pattern from the client side using Inspect, he can still send that data to the database. – remedcu Jul 04 '17 at 10:33
  • 4
    @asterisk a hacker can also track the messages being sent, and use that information to generate their own calls to that location, so it doesn't matter what the front end does, it can be skipped. The API should always do validation on it. – Joo Beck Nov 22 '17 at 22:17
6

use this

<script language="javascript">
document.logOn.onsubmit=validate;

function validate(){

var name=document.logOn.pw.value;
var reg=/[^a-zA-Z0-9\!\@\#\$\%\^\*\_\|]+/;
if(reg.test(name)){              
alert("Your Password Cant Have any thing other than a-zA-Z0-9!@#$%^*_| - Play It    Straight!");
return false;
}               

return true;
}

</script>
5z- -
  • 161
  • 4
3

This should do

<input type="text" name="something" pattern="[a-zA-Z0-9!@#$%^*_|]{0,100}">
AtanuCSE
  • 8,832
  • 14
  • 74
  • 112
3

Invalid Inputs

Many times we want to make validations on an input box for characters that user can type. And other characters will not be entertained in the input box.

Question: Make a input box that accepts digits and spaces only. Also, care for copy-paste (Ctrl +V ) of invalid characters.

The first step is to register event on input tag. But what event type? We are typing characters into it so keypress event looks fine.

<input type="text" id="input"/>
const input = document.getElementById('input');
var currentInputValue = '';
input.addEventListener('keypress', function inputKeypressHandler(e) {
    // keypress event on input box is listened here and this function is triggered
    // which key is pressed, keyPressed = e.which || e.keyCode; 
    const key = e.which || e.keyCode;
    // key code corresponds to digits 0-9 or space then okay
    // 0-9 key code is 48-57
    // space keycode is 32
    const SPACE = 32; // May be just stored somewhere
    const ZERO = 48;
    const NINE = 57;
    // valid digit is b/w 0-9 thus invalid will be lt 0 or gt 9
    const isNotValidDigit = key < ZERO || key > NINE;
    // if key is not a space or not a digit prevent this event
    if (key != SPACE || ( isNotValidDigit ) ) {
        e.preventDefault();
    }
});

This is pretty good solution but this doesn't prevent paste cheats. And that is because the keypress event only records key pressed inside input box. A better event type is requried. input it runs on all input ways including copy paste and drag.

var currentInputValue = '';
input.addEventListener('input', function inputInputEventHandler(e) {
    // use target of event to get value of input
    const target = e.target;
    // we can use regex to check if current input value
    // is valid input
    const DIGITS_SPACE_REGEX = /^[0-9\s]*$/;
    // test if target.value or value of input box now is valid.
    // if value is valid then update currentInputValue 
    // target.value else its is not value and we will
    // ignore this target.value and replace it with 
    // previously valid value currentInputValue
    DIGITS_SPACE_REGEX.test(target.value) 
        ? ( currentInputValue = target.value ) 
        : ( target.value = currentInputValue );
});

This solves our problem of paste but there is one problem here. Say you paste something Ctrl/Cmd + V your current cursor position will be lost and moved to starting. This must not haapen and you must be able to retain cursor position.

// Track cursor position
// cursor position is changed when you type something
const cursorState = {};
input.addEventListener('keydown', function inputKeydownHandler(e) {
    const target = e.target;
    // record the start and end
    cursorState.selectionStart = target.selectionStart;
    cursorState.selectionEnd = target.selectionEnd;
});

now in input handler

// modify
DIGITS_SPACE_REGEX.test(target.value) 
        ? ( currentInputValue = target.value ) 
        : ( target.value = currentInputValue );
 // to
 if (DIGITS_SPACE_REGEX.test(target.value)) {
     currentValue = target.value;
 }
 else {
    target.value = current.value;
    // restore cursor state
    target.setSelectionRange(
        cursorState.selectionStart,
        cursorState.selectionEnd
    );
 }
Aniket Jha
  • 1,751
  • 11
  • 13
0

Try this and revert me back if it works for you

function validate(){
        var name=document.logOn.pw.value;
        var test = new RegExp("[a-zA-Z0-9!@#$%^*_|]");
        if(!name.match(test)){              
           alert("Your Password Cant Have any thing other than a-zA-Z0-9!@#$%^*_| - Play It                     Straight!");
        return false;
  }               
   return true;
}

http://jsfiddle.net/KJEcG/

kundan
  • 73
  • 7
-1

Try this...

if(!/[a-zA-Z0-9!@#$%^*_|]./.test(name)){    
FloatingCoder
  • 1,724
  • 1
  • 12
  • 18