Как я могу проверить, содержит ли поле ввода действительный текст вместо случайных символов в форме? - PullRequest
0 голосов
/ 05 августа 2020

Я хотел бы проверить, набрал ли подписчик осмысленный текст на английском sh в форме вместо случайных символов, например, 'jaghdjagqfsg'.

Под «ерундой» я просто подразумеваю случайные символы, точки / только числа / пробелы, четыре или более согласных, et c. Я просто ищу рецепты или шаблоны регулярных выражений, чтобы не изобретать колесо.

Например, для события onsubmit:

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "jaghdjagqfsg") {
    alert("Please answer the question");
    return false;
  }
}

Ответы [ 2 ]

2 голосов
/ 06 августа 2020

Вот моя идея: мы получаем представление о типичной частоте букв английского sh. Затем мы сравниваем эти частоты с частотами входного текста. (Это можно сделать, вычислив величину « разности векторов »). Если частоты отклоняются выше некоторого порога, мы будем считать, что введенный текст не понятен engli sh. Я использую скопированное стихотворение, чтобы получить представление о нормальных частотах букв - вы можете просто найти более точный список частот для себя. Порог, который я использую, становится более строгим по мере ввода большего количества символов (большая часть гиббери sh отфильтрована, и разрешены наиболее разумные предложения). Поле в правом нижнем углу указывает current score of the entered text / threshold to beat in order to be considered valid.

let textElem = document.querySelector('textarea');
let pElem = document.querySelector('p');

let sampleText = `
Hail to thee, blithe Spirit! Bird thou never wert, That from Heaven, or near it, Pourest thy full heart In profuse strains of unpremeditated art.
Higher still and higher From the earth thou springest Like a cloud of fire; The blue deep thou wingest, And singing still dost soar, and soaring ever singest.
In the golden lightning Of the sunken sun, O'er which clouds are bright'ning, Thou dost float and run; Like an unbodied joy whose race is just begun.
The pale purple even Melts around thy flight; Like a star of Heaven, In the broad day-light Thou art unseen, but yet I hear thy shrill delight,
Keen as are the arrows Of that silver sphere, Whose intense lamp narrows In the white dawn clear Until we hardly see, we feel that it is there.
All the earth and air With thy voice is loud, As, when night is bare, From one lonely cloud The moon rains out her beams, and Heaven is overflow'd.
What thou art we know not; What is most like thee? From rainbow clouds there flow not Drops so bright to see As from thy presence showers a rain of melody.
Like a Poet hidden In the light of thought, Singing hymns unbidden, Till the world is wrought To sympathy with hopes and fears it heeded not:
Like a high-born maiden In a palace-tower, Soothing her love-laden Soul in secret hour With music sweet as love, which overflows her bower:
Like a glow-worm golden In a dell of dew, Scattering unbeholden Its a{:e}real hue Among the flowers and grass, which screen it from the view:
Like a rose embower'd In its own green leaves, By warm winds deflower'd, Till the scent it gives Makes faint with too much sweet those heavy-winged thieves:
Sound of vernal showers On the twinkling grass, Rain-awaken'd flowers, All that ever was Joyous, and clear, and fresh, thy music doth surpass.
Teach us, Sprite or Bird, What sweet thoughts are thine: I have never heard Praise of love or wine That panted forth a flood of rapture so divine.
Chorus Hymeneal, Or triumphal chant, Match'd with thine would be all But an empty vaunt, A thing wherein we feel there is some hidden want.
What objects are the fountains Of thy happy strain? What fields, or waves, or mountains? What shapes of sky or plain? What love of thine own kind? what ignorance of pain?
With thy clear keen joyance Languor cannot be: Shadow of annoyance Never came near thee: Thou lovest: but ne'er knew love's sad satiety.
Waking or asleep, Thou of death must deem Things more true and deep Than we mortals dream, Or how could thy notes flow in such a crystal stream?
We look before and after, And pine for what is not: Our sincerest laughter With some pain is fraught; Our sweetest songs are those that tell of saddest thought.
Yet if we could scorn Hate, and pride, and fear; If we were things born Not to shed a tear, I know not how thy joy we ever should come near.
Better than all measures Of delightful sound, Better than all treasures That in books are found, Thy skill to poet were, thou scorner of the ground!
Teach me half the gladness That thy brain must know, Such harmonious madness From my lips would flow The world should listen then, as I am listening now.
`;

let getCharFrequency = text => {
  
  // Each character increments the value in `f` under the key which is the character
  let f = {};
  for (let char of text.toLowerCase()) f[char] = (f.hasOwnProperty(char) ? f[char] : 0) + 1;
  
  // Normalize this vector by dividing every value by the length
  // Note that `vectorDiffMag` calculates the length if the second
  // vector is `{}` (the "0-vector")
  let len = vectorDiffMag(f, {});
  for (let k in f) f[k] = f[k] / len;
  
  return f;
  
};
let vectorDiffMag = (freq1, freq2) => {
  
  // Returns the magnitude of the vector difference
  // It is essentially a square root of squared differences
  
  let allKeys = new Set([ ...Object.keys(freq1), ...Object.keys(freq2) ]);
  let squareSum = 0;
  for (let key of allKeys) {
    let v1 = freq1.hasOwnProperty(key) ? freq1[key] : 0;
    let v2 = freq2.hasOwnProperty(key) ? freq2[key] : 0;
    let diff = v2 - v1;
    squareSum += diff * diff; // Add the square
  }
  return Math.sqrt(squareSum); // Return the overall square root
  
};

// We only need to compute our "main" frequencies once
let mainFreqs = getCharFrequency(sampleText);

textElem.addEventListener('input', evt => {
  
  // The more characters entered, the lower the threshold becomes
  // The threshold has a horizontal asymptote at 0.55. This means
  // that even very long inputs should be expected to deviate from
  // a "normal" frequency by a magnitude of 0.55.
  let thresh = Math.log(1 + 5 / textElem.value.length) * 0.8 + 0.55;
  
  // Get the magnitude of the vector difference between the "main"
  // frequencies, and the user's input's frequencies
  let diff = vectorDiffMag(mainFreqs, getCharFrequency(textElem.value));
  
  // Render results:
  pElem.innerHTML = `${diff.toFixed(3)} (${thresh.toFixed(2)})`;
  if (diff < thresh) {
    textElem.classList.remove('invalid');
    textElem.classList.add('valid');
  } else {
    textElem.classList.remove('valid');
    textElem.classList.add('invalid');
  }
  
});
textarea {
  position: absolute;
  box-sizing: border-box;
  width: 90%; height: 90%;
  left: 5%; top: 5%;
  resize: none;
  font-size: 150%;
}
textarea.valid { background-color: rgba(0, 150, 0, 0.15); }
textarea.invalid { background-color: rgba(150, 0, 0, 0.15); }
p {
  position: absolute;
  right: 0; bottom: 0;
  padding: 5px; margin: 0;
  background-color: #ffffff;
  box-shadow: inset 0 0 0 1px #000;
  font-size: 120%;
}
<textarea placeholder="type something!"></textarea>
<p>1.000 / Infinite</p>

РЕДАКТИРОВАТЬ: Как указал Джезпез, это вряд ли серебряная пуля! Чтобы получить лучшую валидацию, вам нужно будет использовать этот метод в сочетании с другими методами.

0 голосов
/ 05 августа 2020

Как я уже упоминал в комментарии, во-первых, мы должны определить, что такое «бессмысленный» текст. Потому что системе трудно узнать, если мы не знаем какой-то шаблон о том, что нужно или что не нужно. разрешено, или вы обнаружите общий шаблон, который можно сопоставить с регулярным выражением, чтобы либо отфильтровать, либо принять допустимое имя пользователя.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...