Вы не можете просто ограничить ввод, так как не знаете, что будет печатать пользователь. Вместо этого прослушивайте событие onkeyup
или onblur
, затем вы можете проверить, является ли введенное значение страной. Если нет, то предупредите пользователя каким-либо образом.
Подсказка: Не очищайте ввод, если он недействителен, поскольку пользователи могут быть разочарованы необходимостью повторного ввода длинных названий стран иснова.
Примечание: Массив может содержать не все страны;Я просто скопировал и вставил его из github для нашего удобства
Для моего первого решения я буду прослушивать событие oninput
, а затем проверять, является ли входное значение страной,Если нет, граница ввода станет красной и появится вспомогательный текст, пока пользователь не введет название страны. Если введено название страны, граница станет зеленой.
var countrys = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas"
,"Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands"
,"Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica"
,"Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea"
,"Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana"
,"Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India"
,"Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia"
,"Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania"
,"Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia"
,"New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal"
,"Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles"
,"Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","St. Lucia","Sudan"
,"Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia"
,"Turkey","Turkmenistan","Turks & Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","United States Minor Outlying Islands","Uruguay"
,"Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];
var input = document.getElementById("country");
var helperText = document.getElementById("country-helper-text");
input.addEventListener('input', validate);
function validate(e) {
if (countrys.includes(input.value)) {
input.style.borderColor = "green";
helperText.style.display = "none";
} else {
input.style.borderColor = "red";
helperText.style.display = "block";
}
}
* {
font-family: Arial
}
*:focus {
outline: none
}
#country {
padding: 3px;
font-size: 20px;
border: 2px solid black
}
#country-helper-text {
color: red;
position: relative;
left: 60px;
top: -15px;
font-size: 14px;
display: none;
}
<label>
Country <input id="country" placeholder="Canada" type="text">
<p id="country-helper-text">Invalid Country!</p>
</label>
Второе решение я не покажу, потому что мне понадобится некоторое время, чтобы составить регулярное выражение со всеми странами. Но он использует атрибут pattern
элемента input
для проверки содержимого ввода. Тогда вы могли бы использовать селекторы :valid
и :invalid
css для стилизации ввода и отображения / скрытия вспомогательного текста.