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

Share or Bookmark This Post:


Comments

RSS Comments Feed


K@iTO's Avatar

K@iTO

Hi Nice article.

How can we make thise for Contact Form?

:D

Matt's Avatar

Matt

Shouldn't be too difficult KaiTO, I will have a look at it within the next day or so, and post the results here.

Matt's Avatar

Matt

Code has been updated to work with the contact form as well.

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's Avatar

reey

thanks........

Casper Driver's Avatar

Casper Driver

nice nice thanks...




(optional, not publicly displayed)


(optional)

Subscribe

RSS Feed

Archives

Powered by HTML5

HTML5 Powered with CSS3 / Styling, Multimedia, and Semantics