Search code examples
jqueryregexvalidationzipcode

Basic jQuery syntax problems while trying to validate user input - please advise


I am new to coding as I am sure you will be able to tell from my question as I feel like this should be easy to accomplish, but I have struggled with this for longer than I care to admit and now must ask for guidance.

In the following code, I receive the alert "Not a Zip Code" with every input - whether it is a valid zip code or not.

$("body").on("click", "#searchBtn", function (event) {
event.preventDefault();
// The below is a regular expression (regex) to ensure user enters either a 5 digit or 9 digit US zip code format
var zip = ("^[0-9]{5}(?:-[0-9]{4})?$;");  
var input = $("#userInput").val().trim();
if (input!=zip) {
    alert("Not a Zip Code");  //the end goal is to have the placeholder color turn red
} else {
    alert("Thank you - your entry is valid");  //the end goal is to have the placeholder say "You are searching in zip code " (+ zip)"
};
});

To piggy-back on this issue - when I replace: alert("Not a Zip Code"); With (and I've tried multiple formats at this point but one example is:

$("#userInput").addClass('red');

And for the above I added in my CSS the following:

.red::placeholder {
color: red;
}

I have also searched the similar questions on this board, but they are either more advanced than my current understanding or use programs I am not yet familiar with. Thank you in advance for the assist!


Solution

  • $("body").on("click", "#searchBtn", function(event) {
      event.preventDefault();
      
      var $input = $("#userInput");
      var input = $input.val().trim();
      // Ensure user enters either a 5 digit or 9 digit US zip code format
      var isValid = /^\d{5}(-\d{4})?$/.test(input);
      
      $input.toggleClass('is-invalid', !isValid);
      alert(isValid ? "Thank you - your entry is valid" : "Not a Zip Code");
    
    });
    .is-invalid::placeholder { /* Don't use color-specific classes! */
      color: red;
    }
    <input id="userInput" type="text" placeholder="Enter US ZIP code">
    <button id="searchBtn">SEARCH</button>
    
    <script src="//code.jquery.com/jquery.min.js"></script>