Reputation: 31
I want to allow/whitelist only specific words/codes in textarea.
I've thought using regexp so it is easier to allow codes or some kind of product keys in textarea.
Example I want allow only 2 specific codes in textarea (ALLOW ONLY SPECIFIC WORDS OR CODES):
0FAR12345H00123C00001P
0FAR54321H00321C00001P
So I can't write into textarea (DISALLOWING WRITING RANDOMLY AND RANDOM CODES):
hey
34FAR43..
You can only start in textarea with (Product code can start with only...):
0FAR54321H00321C
0FAR12345H00123C
Regexp example:
/^(0FAR12345H00123C|0FAR54321H00321C|)[a-zA-Z0-9]{6}$/
I didn't find any help in google for allowing specific words or codes in textarea and block other random texts or codes what are not in the whitelist.
Upvotes: 1
Views: 87
Reputation: 4577
You can have a check that could be done onchange
which will fire after changes are made to the textarea.
const CODE = ['0FAR12345H00123C', '0FAR54321H00321C'];
const reg = /^([a-zA-Z0-9]{1,6})$/;
const reg2 = /^(0FAR12345H00123C|0FAR54321H00321C)([a-zA-Z0-9]{6})$/;
// Ensure values been inserted are in correct format
function onInput() {
let values = event.target.value
.split('\n')
.map(v => {
v = v.trim().toUpperCase();
if (v.length <= 16) {
if (CODE[0].substr(0, v.length) != v &&
CODE[1].substr(0, v.length) != v) {
v = v.substr(0, v.length - 1);
}
} else if (!v.substr(16, 22).match(reg)) {
v = v.substr(0, v.length - 1);
}
return v;
}).join('\n');
event.target.value = values;
}
// Truncate any incomplete or incorrect values added to textarea onchange
function onChange() {
let values = event.target.value
.split('\n')
.map(v => {
v = v.trim().toUpperCase();
if (!v.match(reg2)) {
v = '';
}
return v;
}).join('\n');
event.target.value = values;
}
textarea {
width: 400px;
height: 100px;
}
<textarea oninput="onInput()" onchange="onChange()">
0FAR12345H00123C00001P
0FAR54321H00321C00001P
0FAR54321H00321C999999
</textarea>
<br/>
<button>Submit (Fake)</button>
<br/>
<em>Submit to display the onchange results</em>
Hope this helps,
Upvotes: 1