I am writing validation for phone numbers. I need to allow users to write +
character only in the begining of input field and prevent users from writing it later in the field.
In other words:
+11111111
- right,
111111111
- right,
+111+111+
- false,
1111+111+
- false
The problem is that I need to perform validation while typing. As result I cannot analyse whole string after submision, thus it is not possible to fetch the position of +
character because 'keyup' always returns 0
.
I have tryed many approaches, this is one of them:
$('#signup-form').find('input[name="phone"]').on('keyup', function(e) {
// prevent from typing letters
$(this).val($(this).val().replace(/[^\d.+]/g, ''));
var textVal = $(this).val();
// check if + character occurs
if(textVal === '+'){
// remove + from occurring twice
// check if + character is not the first
if(textVal.indexOf('+') > 0){
var newValRem = textVal.replace(/\+/, '');
$(this).val(newValRem);
}
}
});
When I am trying to replace +
character with empty string then it is replaced only once which is not enough, because user might type it a cople of times by mistake.
Here is the link to the fiddle: https://jsfiddle.net/johannesMt/rghLowxq/6/
Please give me any hint in this situation. Thanks!