I'm trying set fixed email mask, but it's not working...
<div data-validate = "Digite seu usuário">
<input type="text" name="usuario">
<span data-placeholder="Email"></span>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script>
$(document).ready(function(){
$('.email').mask('*{A}@test.com.br', {'translation': { "A": { pattern: /[\w@\-. ]/, recursive: true }},reverse: true});
});
</script>
If fixes at one char only "/ I need unlimited, but i don't know what i'm doing wrong.
CodePudding user response:
I suggest you default your input to [email protected]
. When a user focuses the field, select the username so that when the user starts typing they'll overwrite the user but the domain name will stay intact.
Implementing what you want and not losing default behavior of a text field can be very hard. Your current solution breaks a lot of the existing behavior of input fields such as DELETE, arrows, ctrl a, shift arrow, ...
document.querySelector("input[name=email]").addEventListener("focus", (e) => {
const input = e.target;
const currentText = e.target.value;
const indexOfAt = currentText.indexOf("@");
if ( indexOfAt != -1) {
input.setSelectionRange(0, indexOfAt);
}
})
<label>
Name <input name="name" />
</label>
<br />
<label>
Email <input name="email" pattern="[\w @-] @test\.com\.br" value="[email protected]" />
</label>
CodePudding user response:
Solved.
- Got "@" position, then sliced string to remove everything from "@" (always checking if pos == -1) and then insert "@test.com.br";
- In the end i used "setCaretPosition" to set cursor before "@".
Snippet with code below:
<div data-validate = "Digite seu usuário">
<input id="email" type="text" name="usuario">
<span data-placeholder="Email"></span>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script>
$('#email').keyup(function(){
let val = $('#email').val();
let pos = val.indexOf('@');
val = pos >= 0 ? val.slice(0,pos) : val;
pos = pos >= 0 ? pos : val.length;
$('#email').val(val '@test.com.br');
setCaretPosition('email',pos);
});
function setCaretPosition(elemId, pos) {
var elem = document.getElementById(elemId);
// Modern browsers
if (elem.setSelectionRange) {
elem.focus();
elem.setSelectionRange(pos, pos);
// IE8 and below
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>