[英]JSFiddle basic form validation with regex not working
https://jsfiddle.net/gzLeLjmb/ https://jsfiddle.net/gzLeLjmb/
For some reason JSFiddle is throwing an error and I can't work out why? 由于某种原因,JSFiddle抛出错误,我无法弄清楚为什么? I'm just trying to validate an input with a regex for a persons name.
我只是想用正则表达式验证输入的人名。
$("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.");
}
}
})
Everything looks fine to me, except that you should use return false to prevent form from submitting formData. 在我看来,一切都很好,只是您应使用return false来防止表单提交formData。
Also separating javascript logic from the html is recommended. 还建议将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.