Auto Format text after entry in vuejs - javascript

I am trying to auto-format the postal code after entry by the user. The postal code rule is Please use the format A0A 0A0 or 12345. So if the user enters L9V0C7, it auto reformats to L9V 0C7 and when the postal code includes all digits like 12345, it stays as it is. The maxlength should be 6 when the postal code has numbers and alphabets and 5 when the postal code includes only numbers. Help me fix this handlePostalCode method.
The issue I am facing is when I enter L9V0, 0 disappears and I am not able to enter the postal code any further.
<v-text-field
label='Postal Code'
class="required"
v-model='postal_code'
required
#input="handlePostalCode"
validate-on-blur
:rules='postalCodeRules'>
</v-text-field>
postalCodeRules: [
value => /^[A-z]\d[A-z] \d[A-z]\d$|^\d\d\d\d\d$/.test(value) || 'Please use the format A0A 0A0 or 12345'
]
handlePostalCode() {
if (this.postal_code.match(/^[0-9]+$/) != null) {
var replacedInput = this.postal_code.replace(/\D/g, '').match(/(\d{0,3})(\d{0,2})/);
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + '' + replacedInput[2];
}
else {
var replacedInput = this.postal_code.match(/(\w{0,3})(\w{0,3})/);
console.log(replacedInput)
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + ' ' + replacedInput[2];
}
}

The problem is that when the space has been entered after the first three A0A characters, that the regular expression (\w{0,3})(\w{0,3}) cannot cross that space, and will match the empty string with the second capture group, losing out on anything else that follows.
I would suggest the following:
Make the distinction between the first and second postal code rule based on the first character only: if it is a digit, apply the first rule, if not, apply the second rule
The logic you have for the all-numbers case is overly complex: after having removed the non-digit characters, all that is left to do is to clip the string to at most 5 characters. You can use slice for that.
The logic for the second rule could first remove all non-alphanumeric characters (so also spaces would be removed)
Then it could remove any digit that follows immediately after a previous digit, and remove any letter that follows immediately after a previous letter
Finally it could clip the string to 6 characters, and inject the space if there are 4 or more characters.
Here is how your function would look:
function _handlePostalCode() {
this.postal_code = /^\d/.test(this.postal_code)
? this.postal_code.replace(/[^\d]/g, "")
.slice(0, 5)
: this.postal_code.replace(/\W/g, "")
.replace(/(\d)(?:\d+)|([A-Z])(?:[A-Z]+)/gi, "$1$2")
.slice(0, 6)
.replace(/^(...)(.)/, "$1 $2");
}

Related

A convenient way to accept a fixed length number with decimal points

Basically I need to accept a simple decimal value string from a input box.
The length of the input is fixed to 5 digits so it is allowed to accept only 5 digit value.
But if the length of integer part is 5, it should be able to accommodate at least 2 more decimal points or should at least accommodate 2 decimal digits (excluding the decimal separator ) at any time.But the length of the integer part should not exceed 5 digits.
I thought used the following way :
//co2-weight is the class of input field
//by default the max-length and size is 6
$( '.co2-weight' ).keyup(function() {
if($(this).val().indexOf('.')>1)
{
$('.co2-weight').attr('size','9');
$('.co2-weight').attr('maxlength','9');
}
else
{
$('.co2-weight').attr('size','6');
$('.co2-weight').attr('maxlength','6');
}
});
But again here it need to check the length of integer part again and set it to 5.
Is there any shorter or convenient way ?
UPDATE:
The basic problem was to dynamically adjust the length in proper cases which are missing in the answers.
You could use this code, which will not allow:
more than 5 integer digits, nor
more than 2 decimal digits, nor
more than one decimal point, nor
any other character than digits or decimal point
It also applies the attribute changes dependent on whether there is a decimal point.
It responds to the input event, as there are ways of changing the contents without the keyup event firing (e.g. through context menu, mouse,or other device).
$( '.co2-weight' ).on('input', function() {
var good = $(this).val()
// remove bad characters and multiple points
.replace(/[^\d.]|\.(?=.*\.)/, '')
// remove any excess of 5 integer digits
.replace(/^(\d{5})\d+/, '$1')
// remove any excess of 2 decimal digits
.replace(/(\.\d\d).+/, '$1');
if (good !== $(this).val()) {
// Only if something had to be fixed, update
$(this).val(good);
}
var pointPos = good.indexOf('.');
// Determine max size depending on presence of point
var size = good.indexOf('.')>1 ? 8 : 6;
// Use prop instead of attr
$('.co2-weight').prop('size',size);
$('.co2-weight').prop('maxlength',size);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <input class="co2-weight" size="6" maxlength="6">
This is the perfect case where you use regular expressions.
In your case this is the regular expression pattern that you need ^([0-9]{0,5}(\.[0-9]{0,2}){0,1})$
In javascript you would use it this way:
$(this).val().match(/^([0-9]{0,5}(\.[0-9]{0,2}){0,1})$/)
This line alone returns null if it does not find your match. An array of the matches if it does find a match.
If you need to test out this regular expression use https://regex101.com/
Using RegExp you can validate the format of the input like the following example ...
// regular expression to allow 12345.12
var regExp = new RegExp(/^\d{1,5}\.?\d{0,2}$/);
// initialize form elements
$('.valid').hide();
$('.invalid').hide();
$('.submit').prop('disabled', true);
$('.co2-weight').keyup(function() {
// on keyup validate against regular expression
if (regExp.test($(this).val())) {
$('.valid').show();
$('.invalid').hide();
$('.submit').prop('disabled', false);
} else {
$('.valid').hide();
$('.invalid').show();
$('.submit').prop('disabled', true);
}
});
$('.form').submit(function() {
// alert to show input was valid
alert('submitted');
});
.valid {
color: green;
}
.invalid {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type something in the input to see if submit button become enable</p>
<form class="form">
<input type="text" class="co2-weight">
<input type="submit" class="submit">
</form>
<p class="valid">Input format is valid</p>
<p class="invalid">Input format must be <= 99999.99</p>

Restrict text input to number groups separate by a non-consecutive character

I've been doing a lot of searching, chopping and changing, but I'm...slightly lost, especially with regards to many of the regex examples I've been seeing.
This is what I want to do:
I have a text input field, size 32.
I want users to enter their telephone numbers in it, but I want them to enter a minimum of 10 numbers, separated by a single comma. Example:
E.g. 1
0123456789,0123456789 = right (first group is >=10 numbers, second group = >=10 numbers & groups are separated by a single comma, no spaces or other symbols)
E.g. 2
0123456789,,0123456789 = wrong (because there are 2 commas)
E.g. 3
0123456789,0123456789,0123456789 = right (same concept as E.g. 1, but with 3 groups)
I've got the following, but it does not limit the comma to 1 per 10 numbers, and it does not impose a minimum character count on the number group.
$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ','
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Preferably, I'd like to warn the user of where they are going wrong as well. For example, if they try to enter two commas, I'd like to specifically point that out in the error, or if they havent inserted enough numbers, i'd like to specifically point that out in the error. I'd also like to point out in the error when neither a number or a comma is inserted. I'd like to ensure that the tab, and F5 keys are not disabled on the keyboard as well. And very importantly, I'd like to specifically detect when the plus or addition key is used, and give a different error there. I think I'm asking for something a little complex and uninviting so sorry :/
The example code I provided above works pretty well across all browsers, but it doesn't have any of the minimum or maximum limits on anything I've alluded to above.
Any help would be appreciated.
As far as a regex that will check that the input is valid (1-3 phone numbers of exactly 10 digits, separated by single commas), you can do this:
^\d{10}(,\d{10}){0,2}$
Try like the below snippet without Regex
var errrorMessage = '';
function validateLength (no) {
if(!no.length == 10) {
return false;
}
return true;
}
function validatePhoneNumbers (currentString, splitBy) {
if(currentString) {
var isValid = true,
currentList = currentString.split(splitBy);
// If there is only one email / some other separated strings, Trim and Return.
if(currentList.length == 1) {
errrorMessage = 'Invalid Length in Item: 1';
if(validateLength( currentString.trim() )) isValid = false;
}
else if(currentList.length > 1) {
// Iterating mainly to trim and validate.
for (var i = 0; i < currentList.length; i++) {
var listItem = currentList[i].trim();
if( validateLength(listItem ) ) {
isValid = false;
errrorMessage = 'Invalid Length in Item:' + i
break;
}
// else if for some other validation.
}
}
}
return isValid;
}
validatePhoneNumbers( $("#lastname").val() );

password validation script is not working

I am using following script to validate password. Aims For validations are :
Password field should not be empty
Password Length should be between 6 and 10 characters
Password should not contain spaces and special characters
Password should be Alphanumeric.
But With following code , it passes first 3 aims but even after entering Alphanumeric text, it is till alerting:
"Password Should Contain Alphabet And Numbers Both".
Need your help
Code is :
if(document.subForm.password.value==""){
alert("Please Enter Your Desired Password....");
document.subForm.password.focus();
return false;
}
if(document.subForm.password.value.length < 6 || document.subForm.password.value.length > 10){
alert("Password Length Should Be In Between 6 And 10 Characters.");
document.subForm.password.focus();
return false;
}
var re = /^[\w\A-Z]+$/;
if(!re.test(document.subForm.password.value)) {
alert ("Your Password Has Spaces In Between The Words \n\nOr\n\nIt Contains Special Characters.\n\nThese Are Not Allowed.\n\nPlease Remove Them And Try Again.");
document.subForm.password.focus();
return false;
}
var realphanumeric = /^[a-z_A-Z_0-9]+$/;
if (!realphanumeric.test(document.subForm.password.value)){
alert("Password Should Contain Alphabet And Numbers Both");
document.subForm.password.focus();
return false;
}
Aragon0 suggested to use an open-source script from dropbox to check password strength. I recommend checking it out.
If you'd like one regular expresion to check everything:
^\w{6,10}$
Explanation:
From start (^ ) to end ($) of the string...
match only alphanumeric characters ([A-Za-z_0-9]),
with a length of 6-10 characters ({6-10})
If you want to force the user to have at least one number you can do that like this:
^(?![A-Za-z_]+$)\w{6,10}$
Your regex
/^[a-z_A-Z_0-9]+$/
doesn't do what you want. It will match the password "Test" but not "te#st".
You could use two regexes, which both need to match:
/[a-zA-Z]+/
/[0-9]+/
Btw, you should not enforce alphanumeric passwords or length constraints. You could use Dropbox's password strength script (https://github.com/dropbox/zxcvbn)
Some sample code with zxcvbn:
<script src="//cdn.jsdelivr.net/zxcvbn/1.0/zxcvbn-async.js" />
<script>
var result = zxcvbn(document.subForm.password.value);
if(result.entropy<56) // 56 is very secure, you could also lower it to 48 if you need to.
{
alert("Your password is too weak. It would be cracked " + result.crack_time_display);
return false;
}
</script>

Regular expression to verify zip code and checking for invalid characters

I am trying to validate an input for zip codes, now this zip code should work for US, CANADA, UK, all the countries but omit any special characters, so i tried, checking for invalid characters first if that passes then i check for the zip code to either be US or if not just to make sure there are valid characters and not more than 8 (space in between them is ok as long as its now US(which includes - for 5 + 4)
The problem I am having is that 11215 for example is returning as false for the valid character validation and 11215## is returning false also.
Here are my regex:
var reg1 = /^[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]+$/;
var reg2 = /(^\d{5}$)|(^\d{5}-\d{4}$)|(([a-z0-9]{8})*$)/
var isOk = reg1.test("11215"); // returns false!
if(isOk)
{
isOk = isOk && reg2.test("11215");
}
var isOk2 = reg1.test("11215##"); // returns false also!
if(isOk2)
{
isOk2 = isOk2 && reg2.test("11215##");
}
The test for "bad chars", reg1 will always be false unless your string is made entirely of "bad chars". I don't think this is the behaviour you wanted.
var matchBad = /[^\s\da-z\-]/i;
// Match all non-whitespace, non-digit, non-alpabet, non-hyphen
if (false === matchBad.test("11215")) { // no bad chars detected
console.log('pass!');
// continue checking validity..
} else { // bad chars detected
console.log('fail!);
}
Your first regex is testing whether the entire string has those characters. If you want containment, remove the ^ and $ denoting the beginning and ending of your regex:
var reg1 = /[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]/;
This may be only part of the problem but it should get you somewhere. Note I also removed the + since it really only needs to match one character to detect a bad character.
Also another note of design. Your regex that exactly matches the pattern should really be sufficient for testing this. I'm not quite familiar though with the third type of zip, but you might want to make it capture the entire string (with ^ and $)
Javascript should be like below
<script type="text/javascript">
function IsValidZipCode(zipcode) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zipcode);
if (!isValid){
alert('Invalid ZipCode');
document.getElementById("zipcode").value = "";
}
}
</script>
Zipcode text should be
<input id="zipcode" class="zipcode" type="text" placeholder="Your Zipcode?" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required >

How to check If a Tel: area code is correct using jquery?

Hy
I need to check if the given phone area code is correct.
i created a input field, user can insert a tel area code like 0044 oder 0090 and so on.
I restricted the input field to 4 chars.
I need to check after the 4 chars are entered if the area code is correct.
What it should do.
After entering 4 number, the script should check the following things.
Does the entered number equals something like "00{number 2 digit only}" if it doesnt alert("please enter correct tel areacode");
I hope i could explain my problem clear.
How can i do it with javascript or jquery?
Is "0000" a valid area code? It has "00" followed by two digits... but I assume the codes are 00 then a number 10 or higher.
$('input.phone').keyup( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length==4 && (i<9 || i>99) ){
//phone number is invalid
}
});
But I think that blur event will be more useful here, because the above function wouldn't notify the user if he typed only three digits. Notification will appear as soon as the focus is moved aout of the input box, not as soon as the fourth digit was typed. So my proposition is:
$('input.phone').blur( function(){
var num = $(this).val(), i = parseInt(num, 10), valid = true;
if(num.length != 4 || i<9 || i>99 ){
//phone number is invalid, notify the user
}
});
edit: I thought you're validating some kind of area codes specific to your coutry. If you want to validate international calling codes you may wish to look at this list: http://en.wikipedia.org/wiki/List_of_country_calling_codes - there are many +XXX (or 00XXX) numbers and these won't fit into your 4 characters long input. And many numers aren't in +XX (00XX) format, like +1 (001) for USA. I think you should just check if it's + or 00 followed by at least one digit other than zero and let it in.
/^(\+|00)[1-9]/.test( input.value );
Something like this should work:
$('#field').keyup(function() {
var value = $(this).val();
// Restrict length to 4 characters
if(value.length > 4) {
value = value.substring(0, 3);
$(this).val(value);
}
// Test is value equals to "00{number 2 digit only}"
if(/00\d{2}/.test(value)) {
// Is valid
} else {
// Not valid
}
});
I'd avoid using alert on the not valid part, as that would give the user an alert box every time he presses a key.

Categories

Resources