izengod
izengod

Reputation: 1156

jQuery validation not working for input fields

I have jQuery validation for my input fields. But seems like not working :(

$('form')
.submit(function() {

    var name = $.trim($('#TxtName').val());
    var dob = $.trim($('#TxtDesig').val());
    var salary = $.trim($('#TxtSalary').val());

    if (name === "" || dob === "" || salary ==="") {
        alert("All fields are mandatory");
    }
    return false;
});

Here is my html form:

<form class="form-group" method="post">
        <label class="control-label">Employee Name:</label> 
            <input class="form-control" type="text" id="TxtName" name="EmployeeName" value="" /><br />
        <label class="control-label">Designation:</label> 
            <input class="form-control" type="text" id="TxtDesig" name="Designation" value="" /><br />
       <label class="control-label">Salary:</label>
            <input class="form-control" type="date" id="TxtSalary" name="Salary" value=""/><br/>

Upvotes: 1

Views: 2449

Answers (3)

Minhajul Islam
Minhajul Islam

Reputation: 70

You can validate by two process.

process 1: Add following attribute into validated controls as one I edited from your source. Easiest way rest will be responsible of jQuery validation engine.

 <input class="form-control" type="text" id="TxtName" name="EmployeeName" value="" required='' data-msg-required='Please provide name.'/>

Process 2: If you want your controlled validation then you need write piece of code as follows.

$("#form").validate({
    rules:{   //Validation rules work on name attribute
         EmployeeName:{  //Condition Area
               required:true
         }
    },
   messages:{   //user information area
       EmployeeName:
       {
           required:"Please provide Employee Name"  /// Message to user for required fields
       }
   }

}); 

You get more information from jQuery Website

Upvotes: 1

mplungjan
mplungjan

Reputation: 177684

Here is how to code your jQuery validation.

I need to show it in a fiddle since the stacksnippet does not allow form submit

https://jsfiddle.net/mplungjan/n6mcyf6x/

$(function() {
  $('form').on("submit", function(e) {
    var name = $.trim($('#TxtName').val());
    var dob = $.trim($('#TxtDesig').val());
    var salary = $.trim($('#TxtSalary').val());
    if (name === "" || dob === "" || salary === "") {
      alert("All fields are mandatory");
      e.preventDefault();
    }
  });
});

As mentioned by Rhys Bradbury an alternative is to add "required" to each field .
It may however not be supported by older browsers (like IE<10) for example)

http://caniuse.com/#feat=form-validation

Upvotes: 1

Rhys Bradbury
Rhys Bradbury

Reputation: 1707

Why do this in jQuery? Why not use HTML required attribute on form inputs?

ref: http://www.w3schools.com/jsref/prop_text_required.asp

example:

<input placeholder="required a value here please" required/>

FYI this is HTML5

Upvotes: 1

Related Questions