I have seen a lot of functions that format telephone or number (comma and decimals) in stackflow community like this question here and others. Here's what I want to:
Step 1: Maintain a Library for patterns like this:
var library = {
    fullDate : {
        pattern : /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/,
        error : "Invalid Date format. Use YYYY-MM-DD format."
    },
    fullDateTime : {
        pattern : /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}$/,
        error : "Invalid DateTime format. Use YYYY-MM-DD HH:MM (24-hour) format."
    },
    tel : {
        pattern : /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
        error : "Invalid Telephone format."
    }
};
Step 2: Automatically add a character as they type. For exapmple, add a - after 4 numbers in Date.
I have a text field say:
<input type="text" data-validate="fullDate" placeholder="YYYY-MM-DD"/>
And possible place to start script as:
$('body').on('keyup','input',function(){
   var validate = $(this).data('validate');
   var pattern = library[validate].pattern;
    //Some more steps here....
});
But, I cannot make any further because I am new to RegExp. Here's a startup fiddle. Anyone?
Further Notes: I have been able to validate using the following functions but what I want to is automatically make pattern:
function validate(libraryItem, subject){
    var item = library[libraryItem];
    if(item !== undefined){
        var pattern = item.pattern;
        if(validatePattern(pattern, subject)){
            return true;
        } else {
            return item.error;
        }
    }
    return false;
}
function validatePattern(pattern, subject){
    return pattern.test(subject);
}
                It is not as complicated as you think. What you are looking for is JQuery Masked input and other alternative libraries. Here is the documentation. All you need is:
 <input id="date" type="text" placeholder="YYYY-MM-DD"/>
and the script:
 $("#date").mask("9999-99-99",{placeholder:"YYYY-MM-DD"});
Here is demo pen link: http://codepen.io/anon/pen/gpRyBp
To implement validation use this library: https://github.com/RobinHerbots/jquery.inputmask
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With