Hello, I want to make a field for entering a phone number, when I clicked on the field, I appeared + as the first character, after which I could enter 12 more numbers, and you cannot write numbers before the plus and delete the plus, code on a clean (vanilla) JS, through. mask found ( How to set a regular expression for the Ukrainian phone with a static +380 ....? ) in the number entry field , but for the sake of one code I don’t want to connect the library ...

<form action=""> <input type="text" name="tel" placeholder="Номер телефона" required max="13" id="tel"> </form> 

    2 answers 2

    Well ... Validation of the format can be a very non-trivial task, so perhaps a separate plugin, licked by a bunch of people, can be very useful.

     let inp = document.querySelector('#tel'); // Проверяем фокус inp.addEventListener('focus', _ => { // Если там ничего нет или есть, но левое if(!/^\+\d*$/.test(inp.value)) // То вставляем знак плюса как значение inp.value = '+'; }); inp.addEventListener('keypress', e => { // Отменяем ввод не цифр if(!/\d/.test(e.key)) e.preventDefault(); }); 
     input:focus{outline: none;} 
     <form action=""> <!-- Ограничение на длину: maxlength --> <input type="text" name="tel" placeholder="Номер телефона" required maxlength="13" id="tel"> </form> 

    • Thanks, everything works fine, but there is one caveat, it’s very scary or not I don’t know)) you can enter numbers before the plus ... - Ivan
    • in the EI does not work, and you can plus delete ( - Ivan

     var inp = document.getElementById("inp"); inp.onclick = function() { inp.value = "+"; } var old = 0; inp.onkeydown = function() { var curLen = inp.value.length; if (curLen < old){ old--; return; } if (curLen == 2) inp.value = inp.value + "("; if (curLen == 6) inp.value = inp.value + ")-"; if (curLen == 11) inp.value = inp.value + "-"; if (curLen == 14) inp.value = inp.value + "-"; if (curLen > 16) inp.value = inp.value.substring(0, inp.value.length - 1); old++; } 
     <form><input id="inp"></input></form> 

    • you can enter letters, and when you quickly enter do not appear characters () - - Ivan
    • and erase further the first hyphen is impossible. - Sasha Omelchenko
    • corrected it remains to check on the number to enter - perfect