Anna Nguyen
Anna Nguyen

Reputation: 43

How to auto add a hyphen in user input using Javascript?

I am trying to validate and adjust user input for a zip code to match the format: xxxxx OR xxxxx-xxxx Is there a simple way using javascript to add the hyphen (-) automatically if the user enters more than 5 digits?

Upvotes: 0

Views: 5274

Answers (4)

Yogesh
Yogesh

Reputation: 150

You can try using simple javascript function as follows

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <title>JS Bin</title>
  <script>
    function FN_HYPEN(){
    var input = document.getElementById("USER");

  if(input.value.length === 5) {
    input.value += "-";
  }

                       }
  </script>
</head>
<body>
<INPUT ID="USER" TYPE="TEXT" onKeypress="FN_HYPEN();"/>
</body>
</html>

Upvotes: 0

Winson Tanputraman
Winson Tanputraman

Reputation: 3564

Try the following.

function add_hyphen() {
    var input = document.getElementById("myinput");
    var str = input.value;
    str = str.replace("-","");
    if (str.length > 5) {
        str = str.substring(0,5) + "-" + str.substring(5);
    }
    input.value = str
}
<input type="text" id="myinput" value="a" OnInput="add_hyphen()"></input>

Upvotes: 2

John Swaringen
John Swaringen

Reputation: 751

Anna,

The best way to do it would be to use a regular expression. The one you'll need is:

^[0-9]{5}(?:-[0-9]{4})?$

You would ten use something like:

function IsValidZipCode(zip) {
        var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
        if (isValid)
            alert('Valid ZipCode');
        else {
            alert('Invalid ZipCode');
        }
    }

In your HTML call it like this:

<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />

For more on Regular Expressions this is a good article:

Regular Expressions on Mozilla Developers Network

Upvotes: 1

Brent Meeusen
Brent Meeusen

Reputation: 259

Pretty sure there is! Just gotta check how many characters the inputted string has, and if it's 5, add a hyphen to the string :)

var input = document.getElementById("ELEMENT-ID");
input.addEventListener("input", function() {
  if(input.value.length === 5) {
    input.value += "-";
  }
}

Upvotes: 2

Related Questions