HTML Form Field - How to require an input format

醉酒当歌 提交于 2019-12-01 08:33:12

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!

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!