jquery - Javascript string validation. How to write a character only once in string and only in the start? -
i writing validation phone numbers. need allow users write +
character in begining of input field , prevent users writing later in field.
in other words:
+11111111
- right,
111111111
- right,
+111+111+
- false,
1111+111+
- false
the problem need perform validation while typing. result cannot analyse whole string after submision, not possible fetch position of +
character because 'keyup' returns 0
.
i have tryed many approaches, 1 of them:
$('#signup-form').find('input[name="phone"]').on('keyup', function(e) { // prevent typing letters $(this).val($(this).val().replace(/[^\d.+]/g, '')); var textval = $(this).val(); // check if + character occurs if(textval === '+'){ // remove + occurring twice // check if + character not first if(textval.indexof('+') > 0){ var newvalrem = textval.replace(/\+/, ''); $(this).val(newvalrem); } } });
when trying replace +
character empty string replaced once not enough, because user might type cople of times mistake.
here link fiddle: https://jsfiddle.net/johannesmt/rghlowxq/6/
please give me hint in situation. thanks!
to current code fix (@thomas mauduit-blin right there lot more here allow plus symbol @ beginning only), may remove plus symbols preceded character. capture character , restore backreference in replacement pattern:
$(this).val($(this).val().replace(/[^\d.+]|(.)\++/g, '$1'));
see updated fiddle , regex demo.
the pattern updated (.)\++
alternative. (.)
captures character newline group 1 followed 1 or more plus symbols, , contents of group 1 placed during replacement of $1
backreference.
Comments
Post a Comment