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?

1
  • no if you want to show message for each textbox it is imposible Commented Oct 19, 2013 at 13:09

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@RokoC.Buljan thanks for pointing out. I know the difference it's like foreach in some higher-level languages.
@Zaffy rather than displaying the alert each , is it possible to display all the missing fields at the end?
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;

3 Comments

You are missing return true arent you ?
@Zaffy why to use return true; if the default action for onsubmit is the submit itself?
Am not sure if it wont interpret undefined return value as falso and thus if it will work
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

1 Comment

@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.
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.

Comments

-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.

6 Comments

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.jquery.bassistance.de/validate/demo
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
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.
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.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.