HTML Form Field - How to require an input format

2019-02-18 06:37发布

问题:

What I want to do here is require that phone numbers be entered into my HTML form as (XXX) XXX-XXXX and that SS Numbers are entered as XXX-XX-XXXX. Thats it.

The only reason I am doing this is so that the form submission results are consistent and easy exported to Excel.

I have been told to use Javascript to do this but perhaps I am not advanced enough to understand all the steps in doing that.

Can someone please point me in the right direction here keeping in mind that I am a beginner?

Wow thank you so much Ethan and @suman-bogati! I am ALMOST there now! The field now pops an error stating to use the correct format of 555-55-5555. Thats great. But no matter what I enter enter into that field the popup persists. I tried 555-55-5555 and also 555555555 and neither are accepted. Here is the HTML for that field:

<label>
            Social Security Number:
            <input id="ssn" required pattern="^d{3}-d{2}-d{4}$"
                title="Expected pattern is ###-##-####" />
        </label>
</div>
    <script>$('form').on('submit', function(){
        $(this).find('input[name="SocialSecurity"]').each(function(){
        $(this).val() = $(this).val().replace(/-/g, '');
    });
    $(this).find('input[name="ssn"]').each(function(){
        $(this).val() = $(this).val().replace(/-/g, '');
    });
});</script>
    <br />

回答1:

The easiest way to do that is by simply using multiple fields:

<div>
    Phone:
   (<input type="text" name="phone-1" maxlength="3">)
   <input type="text" name="phone-2" maxlength="3">-
   <input type="text" name="phone-3" maxlength="4">
</div>
<div>
    SSN:
    <input type="text" name="ssn-1">-
    <input type="text" name="ssn-2">-
    <input type="text" name="ssn-3">
</div>

While this approach is certainly easy, it's not great. The user has to press tab or click on each field to enter the data, and there's nothing (other than common sense) from preventing them from entering things other than digits.

I always feel that, when it comes to validation, the less you can get in the user's way, the better. Let them enter their phone number in whatever format they like, then you scrub it, removing everything but digits. That way the user can enter "5555551212" or "(555) 555-1212", but the database will always hold "5555551212".

The other thing to consider is that HTML5 offers some nice specific types for phone numbers (but not SSNs). A modern browser will take care of all the input validation and, even better, mobile devices will show the numeric keypad instead of the whole keypad.

Given that, the best way to display your form is this:

<div>
    <label for="fieldPhone">Phone: </label>
    <input type="tel" id="fieldPhone" placeholder="(555) 555-1212">
</div>
<div>
    <label for="fieldSsn">SSN: </label>
    <input type="text" id="fieldSsn" name="ssn" placeholder="555-55-5555" pattern="\d{3}-?\d{2}-?\d{4}">
</div>

If the user has a modern browser, this will handle the user side of the input validation for you. If they don't, you'll have to use a validation library or polyfill. There's a whole list of HTMl5 form validation polyfills here:

https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-web-forms

So all that remains is now to normalize your data when you save it to the database.

The ideal place to do that would be the back end; it doesn't say where your form is going, though, so maybe you don't have any say on how things are processed on the back end. So you can do this in the front end instead. For example, using jQuery:

$('form').on('submit', function(){
    $(this).find('input[type="tel"]').each(function(){
        $(this).val() = $(this).val().replace(/[\s().+-]/g, '');
    });
    $(this).find('input[name="ssn"]').each(function(){
        $(this).val() = $(this).val().replace(/-/g, '');
    });
});

This is not a perfect approach either: if you do validation in this function, and the validation fails, the user will see his or her input replaced by the normalized versions, which can be disconcerting.

The best approach would be to use AJAX and .serialize; not only can you have better control over the UI, but you can do all the validation you want. But that's probably a little beyond what you need to do right now.

Note that phone validation is the trickiest. The HTML5 phone validation is very permissive, allowing people to enter international phone numbers, which can have pretty complicated formats. Even people in the US will sometimes enter phone numbers like "+1 (555) 555-1212", and then you have 8 digits instead of 7. If you really want to restrict them to 7 digits, you'll have to add your own custom validation:

/^\(?\d{3}\)?[.\s-]?\d{3}[.\s-]\d{4}$/

This will cover all the common variations people use (periods, spaces, dashes, parentheses), and still allow only 7-digit US phone numbers.

Here's a jsfiddle demonstrating the HTML5 validation and normalization:

http://jsfiddle.net/Cj7UG/1/

I hope this helps!



回答2:

Use this patterns if you want two patterns should be matched as asked in question.

//for (XXX)-XXX-XXXX
var pattern =  /^\(\d{3}\)\-\d{3}\-\d{4}$/; 

//for XXX-XXX-XXXX
var pattern2 = /^\d{3}\-\d{3}\-\d{4}$/; 

DEMO



回答3:

Here is a complete solution using jquery and jquery tools validator: regex pattern that would handle both cases is :

^(\d{3}-|(\d{3})\s)\d{2}-\d{4}$

HTML:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js" type="text/javascript"></script>
<link href="http://jquerytools.org/media/css/validator/form.css" type="text/css" rel="stylesheet">
<script>
$(function() {
    $("#myform").validator();
});
</script>
</head>
<body>
<form id="myform">
    <input type="text" name="name" pattern="^(\d{3}-|\(\d{3}\)\s)\d{2}-\d{4}$" maxlength="30" />
    <br>
    <input type="submit" name="submit" value="submit" />
</form>
</body>

Click here for demo on jsfiddle



回答4:

use can use sth like this:

<html>
<head>
</head>
<body>
<input type="text" id="ok">
<script>
document.getElementById("ok").onkeypress = function(e){
    var keycodes = new Array(0,48,49,50,51,52,53,54,55,56,57);
    var was = false;
    for(x in keycodes){
        if(keycodes[x] == e.charCode){
            was = true;
            break;
        }
        else{
            was = false;
        };
    };
    var val = this.value;
    if(was === true){
        switch(val.length){
            case 3:
                if(e.charCode !== 0){
                this.value += "-";
                }
                break;
            case 6:
                if(e.charCode !== 0){
                this.value += "-";
                }
                break;
            default:
                if(val.length > 10 && e.charCode !== 0){return false;};
                break;

        };
        val += e.charCode;
    }
    else{
        return false;
    };

};
</script>
</body>

I tested it in ff