Issaki
Issaki

Reputation: 1064

How to highlight valid element when save button is clicked

I am using jQuery validation to validate my form fields. I've two fields, named "comment" & "account name". The comment field has a validation method called required which is set to false whereas the account name field has a validation method called required which is set to true. When the user did not enter any values for both fields & click submit, I want the comment field to be highlighted in green and the account name to be highlighted in red. However, I am not able to highlight the comment field in green. Here is a picture of the error and my code.

Edit: I am still trying to solve this problem. If my explanation is unclear, do let me know!

Screenshot of error

$(document).ready(function() {
  $.validator.setDefaults({
    errorClass: 'help-block',
    highlight: function(element) {
      $(element)
        .closest('.form-group')
        .addClass('has-error');

    },
    unhighlight: function(element, errorClass, validClass) {
      $(element)
        .closest('.form-group')
        .removeClass('has-error')
        .addClass('has-success');
    },
  });

  $('#dataForm').validate({
    rules: {
      commentInput: {
        required: false
      },
      accountNameInput: {
        required: true
      }
    },
    submitHandler: function(form) {
      alert('success');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<form id="dataForm" method="post" action="#">

  <div class="form-group">
    <label class="control-label" for="commentInput">Comments</label>
    <textarea class="commentInput" id="commentInput" cols="20" rows="5"></textarea>
  </div>

  <div class="form-group">
    <label class="control-label" for="accountNameInput">Account name</label>
    <input type="text" id="accountNameInput" name="accountNameInput" placeholder="Account name" class="form-control font-bold" value="" />
  </div>


  <input type="submit" class="btn btn-primary" value="Save" id="saveButton" />

</form>

Upvotes: 0

Views: 113

Answers (1)

toeffe3
toeffe3

Reputation: 83

In your style sheet add this:

.form-group.has-error input {
  background-color: rgba(200,0,0,.2);
}

.form-group.has-success input {
  background-color: rgba(0,200,0,.2);
}

Upvotes: -1

Related Questions