[英]JSFiddle basic form validation with regex not working
https://jsfiddle.net/gzLeLjmb/
由於某種原因,JSFiddle拋出錯誤,我無法弄清楚為什么? 我只是想用正則表達式驗證輸入的人名。
$("document").ready(function() {
function validateForm() {
var userName = $("input[name=userName]").val();
var subject = $("input[name=subject]").val();
var message = $("input[name=message]").val();
if (/^[a-zA-Z ]{2,30}$/.test(userName)) {
alert("Your name is in the correct format");
} else {
alert("Your name can't contain numbers or other characters etc.");
}
}
})
在我看來,一切都很好,只是您應使用return false來防止表單提交formData。
還建議將javascript邏輯與html分開。
$("document").ready(function(){
$('form').on('submit', function() {
var userName = $("input[name=userName]").val();
var subject = $("input[name=subject]").val();
var message = $("input[name=message]").val();
if (/^[a-zA-Z ]{2,30}$/.test(userName)) {
alert("Your name is in the correct format");
}
else{
alert("Your name can't contain numbers or other characters etc.");
return false;
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.