Use jQuery to validate the name and comment fields in sNews
Here's a simple little nugget of jQuery to validate the required fields of your comments forms on sNews. Honestly, jQuery isn't necessary for this basic form checking, but I already use it, so it's easy to add components.
This code just checks that the name field isn't empty, and that the comment textarea contains more than 10 characters, nothing special.
Obviously as this is client-side code, it does nothing if users disable javascript, it is only intended to assist them as the generic comment error page lists four (4) possible reasons why their comment may have failed to submit, this will let them know up front before submitting if the comment is too short or the name is missing.
Here is the vanilla code;
$('#post').submit(function() {
var nameLen = $.trim($('#name').val()).length;
if ($('#text').length > 0) { // comment page
var commentLen = $('#text').val().length;
var emailLen = '1';
} else { //contact page
var commentLen = $('#message').val().length;
var emailLen = $('#email').val().length;
}
var errorMsg = '';
if (nameLen == 0) {
errorMsg = 'You need to add your name!\n';
}
if (emailLen == 0) {
errorMsg = errorMsg + 'You need to add your email!\n';
}
if (commentLen <= 10) {
errorMsg = errorMsg + 'Your comment is too short, write something!';
}
if (errorMsg) {
alert(errorMsg);
return false;
}
});
Obviously you may want to change the language to your own and/or change the minimum length of comments allowed.
Here is the minified version; snews-form-validate.min.js
Simply upload that to the js directory on your server and add it into your index.php file.
<script type="text/javascript" src="/js/snews-form-validate.min.js"></script>
That's it, enjoy
Comments
RSS Comments Feed
K@iTO
How can we make thise for Contact Form?
:D
Matt
Matt
It will check for empty values for names and emails (very basic, no regex... and on contact page only, not for comments so it will work with my gravatar mod), as well as the message/comment text area.
reey
Casper Driver