I tried creating an HTML input (using JavaScript) which takes anything as long as it contains "[...]" and has more than 5 letters. For example "My dog's name is [...] and he's goofy". This is my js code for that.
const sentenceInput = document.createElement('input');
sentenceInput.minLength = '5';
sentenceInput.pattern = ".*\[\.\.\.\].*";
sentenceInput.required = true;
sentenceInput.title = 'Include [...]';
The problem is that the input allows users to submit anything with more than 5 characters and "[." instead of "[...]". What happened and how can I fix that?
I tried using
sentenceInput.pattern = ".*\[\.{3}].*";
or even
sentenceInput.pattern = "/.*\[\.{3}].*/g";
none of it worked.
CodePudding user response:
Changing your pattern to ".*\\[\\.\\.\\.\\].*"
or ".*\\[\\.{3}\\].*"
would get you the desired behaviour:
const inp = document.createElement('input');
Object.entries({
size: '30',
minLength: '5',
pattern: ".*\\[\\.{3}\\].*",
required: true,
title: 'Include [...]',
placeholder:'Submit your sentence with <enter>'
}).forEach(([k,v])=>inp[k]=v);
document.frm.append(inp);
<form name="frm"></form>
The special characters [
, .
and ]
need to be escaped twice with \
since they are firstly interpreted in JavaScript and secondly after the submit event is triggered by the enter key.