Conditional Phone masking Imask.js - javascript

I have below code :
var items = document.getElementsByClassName('phone-mask');
Array.prototype.forEach.call(items, function(element) {
var phoneMask = new IMask(element, {
mask: '000-0000-000',
placeholder: {
show: 'always'
}
});
});
but I need to put conditional masking. For example if phone number starts from 0 then mask: '0000-0000-000' else if phone starts from any other digit then mask: '000-0000-000'. how can this be done ?

Related

How to display vtype warning and don't set field invalid?

This code doesn't work for me because I can't do anything with form.isValid(), so I only need to show the tooltip and color textfield border to show user that I don't recommend to use length > 15, but if code does it anyway, its ok.
// I have some field
{
xtype: 'textfield',
maskRe: /[0-9.]/,
vtype: 'imei',
fieldLabel: 'IMEI:',
name: 'imei',
flex: 1
}
// validation for textfield on keypress
imei: function (v) {
return v.length < 16;
},
imeiText: 'length more then 15 symbols is not recommended'
// validation on save button click
validateForm: function (form) {
if (!form.isValid()) {
// don't save form
}// can't save form because imei is not valid
}
Is there any method to display vtype tooltip, color border and do not set textfield invalid ?
any help in this regards will be appreciated.
you can use listener in your textfield:
listeners: {
change: function (c, newValue, oldValue) {
var tn = newValue.replace(/[^0-9]/g, '');
if (tn.length === 0) {
setTimeout(function () {
c.markInvalid('Imei length must be at least 1 symbol');
}, 100);
}
if (tn.length > 15) {
setTimeout(function () {
c.markInvalid('Imei length more than 15 symbols is not recommended');
}, 100);
}
}
},
There is a timeout, because base field trigger the markInvalid as '' after pushing event.
Look at example on fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2r9h

how avoid 0 to be entered in first position text box using javascript?

i know its possible duplicate. but existing solution is not working out for me.
field should accept like below.
valid - 123,33.00,
100,897,99,
8000
10334
9800,564,88.36
invalid - 001, 0, 01234234, -123, 1.44, .99, 12asdf, 12ASDF, asdf123, ASDF34
codes so far. below code is in ngOninit()
$("#amoutField").on("keypress keyup", function() {
if ($(this.amtField).val() == '0') {
$(this.amtField).val('');
}
});
another method am having is to restrict range
avoidZero(e, field) {
if (field.name === "amoutField ") {
e = (parseInt(e) == 0) ? 0 : e;
this.amoutField = e.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$("#amoutField").val(this.amoutField);
}
}
<input class="wdh100p" type="text" id="amoutField" name="amoutField " value="" maxlength="5"
[ngModel]="amoutField " (ngModelChange)="avoidZero($event, amts)">
You can use a regular expression and simply remove all the leading zeros when the input value changes...
$("#amountField").on("input", function() {
this.value = this.value.replace(/^[0]*/, "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="amountField" />
Note: Using the input event covers all possible ways the value of the input can change (copy/paste, drag/drop etc.)
You need to separate the events to handle different situations:
Situations
User typing zero at first position
User dragging value from another field to this field.
User typing number and then typing zero at first position.
$("#amoutField").on("keydown", function(e) {
if ($(this).val().trim().length === 0 && e.keyCode === 48) {
e.preventDefault();
}
}).on("keyup", function() {
handleKeyupFocus(this);
}).on('focus', function() {
handleKeyupFocus(this);
}).on('drop', function() {
var $self = this;
setTimeout($.proxy(function() {
handleKeyupFocus($self);
}), 0);
});
var handleKeyupFocus = function(target) {
while ($(target).val().startsWith("0")) {
$(target).val($(target).val().substring(1));
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Try to drag, paste zeros from another field, clipboard, Etc.</p>
<input id="amoutField">
Are you sure that "0" is an invalid case?
If not, the simplest approach is:
function isValid(text) {
return parseFloat(text).toString() === text;
}
Test:
var test = ["-123", "238", "100", "10336", "101010", "10001", "-001", "0", "01234234"];
var results = test.map(t => isValid(t));
Output:
[ true, true, true, true, true, true, false, true, false ]
Bonus: in case zero is an invalid case, just filter it out.
function isValid(text) {
var numericValue = parseFloat(text).toString();
return numericValue === text && numericValue !== "0";
}

Script doesn't work if misplaced in jQuery

i will create website with validate in input field, i used Mottie Keyboard in every input field, and i use validation on it. i will create disable button when validation is not correct. And I get a script for it, directly from github page mottie keyboard. I want is if the validation was not correct then the button in a virtual keyboard can not be pressed. Here's the script:
var toggleKeysIfEmpty = function( kb ) {
var toggle = kb.$preview.val() === '';
console.log( toggle, kb.$preview.val() );
kb.$keyboard
.find('.ui-keyboard-bksp')
.toggleClass('disabled', toggle)
.prop('disabled', toggle);
};
And this my script before adding script above:
$(function() {
// change default navigation keys
$('#jkeyboard2, #jkeyboard').keyboard({
layout: 'num',
// setting alwaysOpen does odd things with input focus on initialization
// best to leave it false and focus on the desired input
// alwaysOpen: true,
autoAccept: true,
usePreview: false,
position: {
of: $(window),
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
my: 'center bottom',
at: 'center bottom',
at2: 'center bottom'
},
maxLength: 4,
layout: 'custom',
customLayout: {
'normal': ['1 2 3', '4 5 6', '7 8 9', '0 . {b}'],
},
visible : function(e, keyboard) {
toggleKeysIfEmpty( keyboard );
},
tabNavigation: true,
initialFocus: false,
initialized: function() {
setTimeout(function(){
$('#jkeyboard').focus();
}, 200);
},
change: function(e, keyboard, el) {
if (keyboard.$el.val().length >= 4) {
// switchInput( goToNext, isAccepted );
keyboard.switchInput(true, true);
} else if (keyboard.$el.val() === "" && keyboard.last.key === "bksp") {
// go to previous if user hits backspace on an empty input
keyboard.switchInput(false, true);
}
}
})
});
$(document).ready(function() {
$('#jkeyboard').bind('keyboardChange', function (e, keyboard, el) {
if (validatePhone('jkeyboard')) {
$('#spnPhoneStatus').html('');
$('#spnPhoneStatus').css('color', 'green');
} else {
$('#spnPhoneStatus').html('<b>Wrong Number</b>');
$('#spnPhoneStatus').css('color', 'red');
}
});
});
function validatePhone(jkeyboard) {
var a = document.getElementById(jkeyboard).value;
var filter = /^0(?:8(?:(?:1(?:[789][0-9]{0,9})?|3(?:[1238][0-9]{0,9})?|5(?:9[0-9]{0,9})?|7(?:[78][0-9]{0,9})?)?)?)?$/;
//var filter = /^0([8]([1357]([123789]([0-9]{0,8}))?)?)?$/;
if (filter.test(a)) {
return true;
} else {
return false;
}
}
I want disable backspace button if validation was not correct, so i added the script. And become like this:
$(function() {
// change default navigation keys
$('#jkeyboard2, #jkeyboard').keyboard({
layout: 'num',
// setting alwaysOpen does odd things with input focus on initialization
// best to leave it false and focus on the desired input
// alwaysOpen: true,
autoAccept: true,
usePreview: false,
position: {
of: $(window),
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
my: 'center bottom',
at: 'center bottom',
at2: 'center bottom'
},
maxLength: 4,
layout: 'custom',
customLayout: {
'normal': ['1 2 3', '4 5 6', '7 8 9', '0 . {b}'],
},
visible : function(e, keyboard) {
toggleKeysIfEmpty( keyboard );
},
tabNavigation: true,
initialFocus: false,
initialized: function() {
setTimeout(function(){
$('#jkeyboard').focus();
}, 200);
},
change: function(e, keyboard, el) {
if (keyboard.$el.val().length >= 4) {
// switchInput( goToNext, isAccepted );
keyboard.switchInput(true, true);
} else if (keyboard.$el.val() === "" && keyboard.last.key === "bksp") {
// go to previous if user hits backspace on an empty input
keyboard.switchInput(false, true);
}
}
})
});
$(document).ready(function() {
$('#jkeyboard').bind('keyboardChange', function (e, keyboard, el) {
if (validatePhone('jkeyboard')) {
$('#spnPhoneStatus').html('');
$('#spnPhoneStatus').css('color', 'green');
} else {
$('#spnPhoneStatus').html('<b>Wrong Number</b>');
$('#spnPhoneStatus').css('color', 'red');
var toggleKeysIfEmpty = function( kb ) {
var toggle = kb.$preview.val() === '';
console.log( toggle, kb.$preview.val() );
kb.$keyboard
.find('.ui-keyboard-bksp')
.toggleClass('disabled', toggle)
.prop('disabled', toggle);
};
}
});
});
function validatePhone(jkeyboard) {
var a = document.getElementById(jkeyboard).value;
var filter = /^0(?:8(?:(?:1(?:[789][0-9]{0,9})?|3(?:[1238][0-9]{0,9})?|5(?:9[0-9]{0,9})?|7(?:[78][0-9]{0,9})?)?)?)?$/;
//var filter = /^0([8]([1357]([123789]([0-9]{0,8}))?)?)?$/;
if (filter.test(a)) {
return true;
} else {
return false;
}
}
it's doesn't work, and i try put the code i get at the top of my code. it's work but backspace button can not be pressed from the start. Anyone can fix it?
Here's my fiddle: DEMO
I have changed your code to update the fiddle here : you wanted to
disable backspace button if validation was not correct
so here's what I did:
I renamed toggleKeysIfEmpty to toggleBackspaceKey and changed its implementation to add the CSS classes to render the button correctly depending on the desired state:
var toggleBackspaceKey = function( kb, toggle ) {
console.log( toggle, kb.$preview.val() );
var $bkSpaceBtn = kb.$keyboard.find('.ui-keyboard-bksp');
if (toggle) {
$bkSpaceBtn
.attr({
'disabled': 'disabled',
'aria-disabled': 'true'
})
.removeClass(kb.options.css.buttonHover)
.addClass(kb.options.css.buttonDisabled);
} else {
$bkSpaceBtn
.removeAttr('disabled')
.attr({
'aria-disabled': 'false'
})
.addClass(kb.options.css.buttonDefault)
.removeClass(kb.options.css.buttonDisabled);
}
};
I changed the implementation of the bksp keyaction handler to ensure that if it's invoked when the button is disabled, no action is executed. The handler for the backspace will be invoked if you press the corresponding key or if you double click on the backspace button in the keyboard even when it's disabled (this might be a bug). Here is the handler code: if the backspace button is enabled it simply invokes the default backspace processing handler. Also, this function is invoked once from the visible callback:
var processBkSpcKey = function(kb) {
var originalBkSpaceHandler = $.keyboard.keyaction.bksp;
$.keyboard.keyaction.bksp = function(base) {
// If the backspace button is disabled, do not process it.
var $bkSpaceBtn = kb.$keyboard.find('.ui-keyboard-bksp');
if($bkSpaceBtn.hasClass(kb.options.css.buttonDisabled)) {
return false;
}
return originalBkSpaceHandler.apply(kb, arguments);
}
};
With these changes in place, the backspace button is disabled if the input is empty or if the validation fails, in this case though, how would the user clear the contents of the input?

Ckeditor character limitation with charcount plugin

How can i prevent users to enter new characters after max character limit is reached ?
Ckeditor charcount plugin just shows me the remaining characters, i want it to stop at 0. But it goes minus integers.
Here's my html code.
<textarea id="myTextEditor1" name="myTextEditor"></textarea>
<script type="text/javascript">
CKEDITOR.replace('myTextEditor1', {
height: 200,
extraPlugins: 'charcount',
maxLength: 10,
toolbar: 'TinyBare',
toolbar_TinyBare: [
['Bold','Italic','Underline'],
['Undo','Redo'],['Cut','Copy','Paste'],
['NumberedList','BulletedList','Table'],['CharCount']
]
});
</script>
Do i have to use onChange plugin ? If i have to how can i limit users entering new characters ?
I used the ckeditor jQuery adapter for this.
<textarea id="myTextEditor1" name="myTextEditor"></textarea>
<script type="text/javascript">
$(function () {
var myEditor = $('#myTextEditor1');
myEditor.ckeditor({
height: 200,
extraPlugins: 'charcount',
maxLength: 10,
toolbar: 'TinyBare',
toolbar_TinyBare: [
['Bold','Italic','Underline'],
['Undo','Redo'],['Cut','Copy','Paste'],
['NumberedList','BulletedList','Table'],['CharCount']
]
}).ckeditor().editor.on('key', function(obj) {
if (obj.data.keyCode === 8 || obj.data.keyCode === 46) {
return true;
}
if (myEditor.ckeditor().editor.document.getBody().getText().length >= 10) {
alert('No more characters possible');
return false;
}else { return true; }
});
});
</script>
The keyCode check is to allow backspace and delete key presses. To use the jQuery adapter, don't forget to insert it:
<script src="/path-to/ckeditor/adapters/jquery.js"></script>

Adding a pop-up box in the middle of the screen when fields are left blank

This so far will add the word empty to fields left blank, but i need to add a pop-up at the top-middle of the screen stating "please fill in all fields before submitting" in its own custom box i can change using css to style it.
this seems like a very simple thing to do although i just cant find out how.
if the following code is horrible its what has been given to me for the exercise, with zero documentation on how to perform the task.
do i need to create a div for the pop up box and a function to execute it? by calling the fuction in the if statement.
i apologies if i have been vague or made no sense as this is still very new to me (im sure thats obvious haha)
thanksguys!
var requiredFields = [ "firstname", "lastname", "email", "message" ];
function checkContactForm() {
var theForm = document.forms[ 0 ];
for ( var i in requiredFields ) {
var fieldName = requiredFields[ i ];
if ( !theForm[ fieldName ].value || theForm[ fieldName ].value == "Error" ) {
theForm[ fieldName ].style.color = "#f66";
theForm[ fieldName ].value = "Error";
var emptyFields = true;
}
}
if ( !emptyFields ) { theForm.submit(); }
}
function resetField( theField ) {
if ( theField.value == "Error" ) {
theField.value = "";
}
theField.style.color = "#000";
}
Why don't you use a jquery ui .dialog like: http://jsfiddle.net/csdtesting/aL14evyk/
$("#dialog-message").dialog({
modal: true,
draggable: false,
resizable: false,
position: ['center', 'top'],
show: 'blind',
hide: 'blind',
width: 400,
dialogClass: 'ui-dialog-osx',
buttons: {
"I've read and understand this": function() {
$(this).dialog("close");
}
}
});

Categories

Resources