简体   繁体   中英

Prevent unallowed pasting into text-input

I'm trying to prevent the user from pasting unallowed text into an input field. The Input is a randomly generated 8 digit Code, that contains letters and numbers.

But I don't want the user to paste any text that contains other characters.

my input field:

<input type='text' id='form-code-field' name='code' maxlength='8'>

Note:

I'm not looking for something like the readonly attribute, because the user still has to input alphanumeric text into the field.

You could test value input using a regex on input event:

 $('#form-code-field').on('input', function(){ if(!/^[a-z0-9]+$/i.test(this.value)) this.value = $(this).data('oldValue') || ""; else $(this).data('oldValue', this.value); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type='text' id='form-code-field' name='code' maxlength='8'>

For HTML5 browsers you can also do this, and no script required:

<input type='text' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9">

This will not stop someone from write non valid characters, the pattern will be evaluated on submit and will abort the submit with a message if not matched.

Update

I added a plain javascript version for those who don't use jQuery, which works globally on a form. Just set the "pattern" on a input field and it kicks in.

The script also works on input on non HTML5 browsers.

A "safety" note:

As a client side evaluation, this by no means is 100% safe to just store server side, you always need to check whats posted before doing anything with it.

 document.getElementById('form').addEventListener('input', function(e){ if (e.target.pattern && e.target.pattern.length > 0) { var regex = new RegExp(e.target.pattern,"i"); if(!regex.test(e.target.value)) { if (e.target.value.length > 0) { e.target.value = e.target.getAttribute('data-old-value') || ""; } else { e.target.setAttribute('data-old-value', ""); } } else { e.target.setAttribute('data-old-value', e.target.value); } } }, false);
 <form id="form"> Only alphanum (max 8): <input type='text' id='form-code-field' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9"><br /><br /> Any character (max 5): <input type='text' id='form-code-field' name='code' maxlength='5' ><br /> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM