Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp to automatically format Pattern

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);
}
like image 394
tika Avatar asked Jun 07 '15 21:06

tika


Video Answer


1 Answers

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

like image 191
Dinesh Devkota Avatar answered Oct 23 '22 06:10

Dinesh Devkota