Reputation: 49
https://jsfiddle.net/gzLeLjmb/
For some reason JSFiddle is throwing an error and I can't work out why? 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.");
}
}
})
Upvotes: 0
Views: 653
Reputation: 1360
Everything looks fine to me, except that you should use return false to prevent form from submitting formData.
Also separating javascript logic from the html is recommended.
$("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;
}
});
});
Upvotes: 1