5

I have an HTML form with a button which when clicked, it will check whether or not the fields are empty. Here is part of my code which does the validation(it works):

var errorMessage ="";
if (document.getElementById('username').value == "")
    {
    errorMessage += "Please enter a username \n";
    document.getElementById('username').style.borderColor = "red";
    }
if (document.getElementById('fname').value == "")
    {
    errorMessage += "Please enter a first name \n";
    document.getElementById('fname').style.borderColor = "red";

}
if (document.getElementById('lname').value == "")
    {
    errorMessage += "Please enter a last name \n";
    document.getElementById('lname').style.borderColor = "red";

    }
if (errorMessage != "")
    {
alert(errorMessage);
}

My problem is because I have more fields which require validation, I am wondering if there is a better way of doing this rather than having so many if statements (I'm trying to have as little code as possible). I was thinking of using a switch case statement but would that work? Any suggestions?

littledevils326
  • 689
  • 3
  • 11
  • 19

5 Answers5

2

You can use a table with data of fields and then just iterate over it.

var fields = [[document.getElementById("username"),"Please Enter Your Username"],
              [document.getElementById("fname"),   "Please Enter Your First Name"],
              [document.getElementById("lname"),   "Please Enter Your Last Name"]];

function Check()
{
    var error = [];

    for (var i in fields)
    {
        if (fields[i][0].value == "")
        {
            error.push(fields[i][1]);
            fields[i][0].style.borderColor = "red";
        }
    }

    if (error.length)
        window.alert(error.join(",\n"));

    return !error.length;
}

Note: probably you want o make sure that the value isnt empty so I would suggest you using something like: fields[i][0].value.replace(/\s/g, "") == "" instead.

Zaffy
  • 16,801
  • 8
  • 50
  • 77
  • 2
    Just as sidenote: [Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – Roko C. Buljan Oct 19 '13 at 13:37
  • @RokoC.Buljan thanks for pointing out. I know the difference it's like `foreach` in some higher-level languages. – Zaffy Oct 19 '13 at 13:38
  • @Zaffy rather than displaying the alert each , is it possible to display all the missing fields at the end? – littledevils326 Oct 19 '13 at 13:53
1

I'd go with this way, using data-* attribute to store the error messages:

Live demo

<form id="myForm" name="myForm">
   <input type="text" name="username" id="username" data-err="Please enter a username" />
    <input type="text" name="fname" id="fname" data-err="Please enter a first name" />
    <input type="text" name="lname" id="lname" data-err="Please enter a last name"/>

    <input type="submit" />
</form>

function formValidator(){

  var inputs = this.getElementsByTagName('input');
  var allErrors = '';

  for(var i=0; i<inputs.length; i++) {
      var el = inputs[i];
      var data = el.dataset.err;
      if(data && el.value.trim() === ''){
          allErrors += data +'\n';
      }    
  }
  if(allErrors){
      alert(allErrors);
      return false;
  }else{
      alert('All fine. Submit!'); 
  }

}


document.myForm.onsubmit = formValidator;
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

If your using html5 try adding required attribute on the html element. It is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form.

Something like : <input type="text" name="usrname" required>

Demo

super
  • 2,288
  • 2
  • 21
  • 23
  • @sujith : - Firefox and IE10 support some of it. - Opera and Chrome support all of it. - Safari supports all of it too, but form validation is disabled by default. – super Oct 19 '13 at 14:51
0

Since every other answer either suggests writing your own validation code, or use some big, heavy frameworks like Angular, I'd like to suggest using small, specialized libraries for validtion, like Parsley.js (although it depends how do you define "small" - Parsley ships either in jQuery/Zepto dependand version or standalone weighting around 42kB).

Using Parsley, your could write very little code to validate a form. Just load this library and then use rules defined in custom HTML attributes, like data-type="email".

Here's an example from their webpage (I stripped down all parts not important in your question. Here is a full example, for your reference):

<form id="demo-form" data-validate="parsley">
    <input 
         type="text" 
         name="email" 
         data-trigger="change"         <!-- parsley's attributes: data-... -->
         data-required="true" 
         data-type="email" />          <!-- E-mail rule -->

    <input 
         type="text" 
         name="website" 
         data-trigger="change" 
         data-type="url" />            <!-- URL rule -->

    <textarea 
         name="message" 
         data-trigger="keyup" 
         data-rangelength="[20,200]">
    </textarea>
</form>

There are, of course, other libraries which can do same thing, like validate.js, but I prefer Parsley.js' aproach using data- attributes - it's a very clear separation of concerns and nice example of "extending" HTML.

kamituel
  • 34,606
  • 6
  • 81
  • 98
-1

If you want to go with plain Javascript without any Client side Javascript framework, or HTML5 you cant do that.

You can look at HTML5 as suggested by @bios, or you can use frameworks such as:

validate.js

html5 libraries

These would ease your validation requirements and make code cleaner.

If you want something more sophisticated, you can go for full fledged client side MVC frameworks such as:

AngularJS

Backbone.js

But these are too heavy if you want just form validation.

Praveenram Balachandar
  • 1,587
  • 1
  • 13
  • 16
  • it is possible in html5 but it will not support in all browsers better to go with jquery form validate and you can get more controll too.http://jquery.bassistance.de/validate/demo/ – Sujith Wayanad Oct 19 '13 at 13:27
  • `If you want to go with plain Javascript without any Client side Javascript framework, or HTML5 you cant do that.` What are you talking about ? Frameworks are written in plain javascript so show me a thing a framework can do and I cannot with plain JS – Zaffy Oct 19 '13 at 13:32
  • While jquery form validate is quite sufficient, I would argue the need for jquery just to do form validation. Since the code sample uses no javascript library / jquery, I would just use something even more leaner and lighter than jquery form validate like validate.js for instance. Using jquery.min v1.10 (90kb), jquery.validate.min (21kb) you're effectively downloading 110kb vs using something like validate.js its just 2kb. – Praveenram Balachandar Oct 19 '13 at 13:34
  • The question was more around how to write as less code as possible to achieve this. I agree that frameworks are written in plain Javascript, my point with that statement was, without using HTML5 or some (micro)framework, it is not possible to do the validation with minimal code written. – Praveenram Balachandar Oct 19 '13 at 13:37
  • Adding a libraries is not less code its more....you might write less but your website has much larger chunk of code to load.. a library for such a minor thing is quite pointless. – Sir Oct 19 '13 at 15:06
  • Thats precisely my point, thats why I suggested the validate.js, which simplifies writing form validation code and its very light weight. – Praveenram Balachandar Oct 19 '13 at 15:08