For example, there is a string: "1, 12, string, 12" - how to catch the word "string", and make sure that the user does not enter numbers or other words, signs, except 1-12, and ",".

And where can I insert an alert to notify the user that he has not correctly entered data, for example a word?

  • probably somewhere \ d + (\ s *, \ s * \ d +) + - KoVadim
  • one
    > And where should I insert an alert to notify the user that he has entered the data incorrectly, for example, a word? It will be good to highlight the input reds and display a small hint next to it. - etki
  • Sorry, for the first time here) var str = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12" - the correct string is var str = "1, 2, 3, 4, 5, 9, 10 "- the correct string var str =" 1, 2, 13, 4, 5, 9, 10 "- the wrong string, there is a number> 12 var str =" 1, 2, text, 4, 5, 9, 10 "- incorrect string, contains the word - SunDay
  • function Control () {var str = document.getElementById ("Field"); var re = / ([1-9] | 1 [0-2]) $ /; if (str! = null) {if (str.search (re)! = -1) {alert ("Correct data"); } else {alert ("Incorrect data!"); }} else {}} - SunDay

2 answers 2

And why is it necessary to regular? You need to determine the number - here and do it honestly, with numbers.

Divide by comma, rasparte.

return s.split(",") .map(function(l){ return parseInt(l, 10); }) .every(function(n) { return !isNaN(n) && 0 < n && n < 13; }); 

Check .

     "0, 1, 12, строка, 12,13,14".split(/\s*,\s*/).filter(function (item) { return /^([1-9]|1[0-2])$/.test(item); }).join(", ") // returns: "1, 12, 12"