Caitlin
Caitlin

Reputation: 541

Check Field Validity and Fields Filled Before Submission?

I am revising this question as I have changed things.

I have a form with a few fields, three of which have regex validation. I also have a function which checks if all fields are filled before the submit button is enabled, this works fine. However if the fields are filled but the invalid fields ae invalid, I can still submit the form. I want to know if I am able to merge my functions so that I can check if the fields are filled AND valid before enabling the submit button?

I have tried adding an extra && clause but this doesn't work, and I tried to implement the jQuery validate plug-in but it seemed very limited and I can't validate a postcode using it.

Here is a reduced version of my project:

// ~~~ postcode validation

function validatePostcode(postcode) {
  var pcode = /^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$/;
  return pcode.test(postcode);
}

function validateP() {
  var postcode = $("#postcode").val();

  if (validatePostcode(postcode)) {
    $("#postcode").removeClass("is-invalid");
    return true;
  } else {
    alert('Please enter a valid postcode');
    $("#postcode").addClass("is-invalid");
  }
  return false;
}

// ~~~ validate if form is filled completely, toggles submit & edit button

$(document).on('change keyup invalid', '.required', function(e) {
  var disabled = true;

  $(".required").each(function() {
    var value = this.value;

    if ((value) && (value.trim() != '')) {
      disabled = false;
      $('.toggle-disabled').prop("disabled", false);
    } else {
      disabled = true;
      $('.toggle-disabled').prop("disabled", true);
      return false;
    }
  });


});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<div class="col-md-6">
  <input type="text" id="postcode" class="input postcode form-control required" onchange="validateP()" placeholder="Post Code" name="postcode" required>
</div>
<div class="col-md-6">
  <input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit" disabled>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Upvotes: 0

Views: 234

Answers (1)

Atul kumar Mishra
Atul kumar Mishra

Reputation: 19

Use below regex:

/^([0-9a-zA-Z\-\._]+)@([0-9a-zA-Z\-\._]+)\.([a-zA-Z]){2,7}$/

Upvotes: 1

Related Questions