This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
I want the user to only be able to enter English characters, the code below works but on a mac if you hold the letter "a" for example you can insert accented characters such as "รก". I've tried a few different approaches with keydown, keyup etc but even on the release of the key it thinks the value that was entered is "A" so it gets past the regex. Anyone know whats going wrong or a better way on how to do this please?
$('.monogram-letters').on("keypress", function(e) {
var englishAlphabet = /[A-Za-z]/g;
var key = String.fromCharCode(e.which);
if (englishAlphabet.test(key)) {
console.log('true');
return true;
} else {
console.log('false');
}
return false;
});
$('.monogram-letters').on("paste", function(e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="" class="monogram-letters valid" maxlength="3" id="options-41-container" name="options[41]" data-category="41" data-val="type your letters (up to 3)" required="" aria-required="true" aria-invalid="false">
You can instruct an input text to accept only english characters doing so:
<input pattern="[a-z]" />
You will want to validate server-side as well obviously.
The solution I ended up going for was to check the final string and then just emptying the input if it had an accented character
var $monogramInput = $('.monogram-letters');
var englishAlphabet = /^[a-z]+$/i;
$monogramInput.on("keypress", function(e) {
var key = String.fromCharCode(e.which);
if(englishAlphabet.test(key)) {
return true;
}
return false;
}).blur(function() {
var enteredValue = $(this).val();
if(!enteredValue.match(englishAlphabet)) {
$(this).val('');
}
});
Related
<input class="name-input" type="text"/>
I assume that there is some kind of regular expression to solve this problem, but I could not find on the Internet which one..
I will be very grateful if you help =')
Updated: the main question is how to prevent the user from entering the character "`" in the Input field. I don't understand hot to do this.
You can add an eventlistener to the input field and check for any charachter, that you don't want for each keystroke.
I made a quick demo: https://codesandbox.io/s/vigilant-leaf-h2syxv?file=/index.html:115-160
let item = document.querySelector(".name-input");
item.addEventListener("keypress", (e) => {
if (e.key === "~" || e.key === "`") {
e.preventDefault();
}
});
<input class="name-input" type="text" />
So you should start by making a list of the special characters that you would to prevent users from using them, i assume that your list contains : [~,',",(,),`].
Then you can use this :
let name = document.querySelector('.name-input')
let regex = "[`'"()~]"
if ( name.match(regex) ){
console.log('There was a match');
} else {
console.log('NO match');
}
I have a problem
I make a check when you enter upper or lower case letters in the text input to warn that letters cannot be entered but only numbers.
how to make i only enter numbers in the input?
<input type="text" id="texter">
<button onclick="checker()">
START
</button>
checker = () =>{
var texter = document.getElementById('texter').value;
if(texter.search(/[a-z]/)){
alert("letters");
return false;
}
else if(texter.search(/[A-Z]/)){
alert("letters big");
return false;
}
else{
return true;
}
}
For the best user experience, using type="number" on your input is the best bet.
<input type="number" />
If you need it to be a "text" type, one thing you can do is strip any non-numeric character from the string and set the value of the textbox to this string:
const textbox = document.querySelector('#texter');
textbox.onkeyup = event => {
const stripped = event.target.value.replace(/\D/g,'');
textbox.value = stripped;
}
<input id="texter" />
sorry but why don't just use number type of the input
<input type='number'id='texter' />
here you don't need to check for number this input just accept numbers
So I have this problem. I want bootstrap tagsinput to only accept letters, comma, and enter key. How to solve this problem? I use this bootstrap: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/
HTML:
<div class="form-group">
<div class="col-sm-4">
<input type="text" id="myinputs" class="form-control" name="skills" placeholder="Enter skill(s), separate each with a comma" data-role="tagsinput">
</div>
</div>
JavaScript:
$(document).ready(function() {
$('#myinputs').keypress(function(event){
var inputValue = event.charCode;
if (!(inputValue >= 65/*A*/ && inputValue <=90/*Z*/) && !(inputValue >=97/*a*/ && inputValue <= 122/*z*/) && (inputValue != 44/*comma*/ && inputValue != 13/*enter key*/)) {
event.preventDefault();
}
});
});
When there is no tagsinput, the javascript code is working. How to solve this problem?
Here is the simple way, but css is not included.
$('input').tagsinput({
freeInput: true
});
$('input').on('beforeItemAdd', function(event) {
// event.cancel: set to true to prevent the item getting added
event.cancel = !(/^[0-9A-Za-z\.,\n]+$/.test(event.item));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/TimSchlechter/bootstrap-tagsinput/master/src/bootstrap-tagsinput.js"></script>
<input type="text" id="category" data-role="tagsinput" />
Probably you can try different approach and use beforeItemAdd event to check the content of new item. If it contains unwanted charactes you cancel its addition.
$('input').on('beforeItemAdd', function(event) {
// check item contents
if (!/^[a-zA-Z,]+$/.test(event.item)) {
// set to true to prevent the item getting added
event.cancel = true;
}
});
You cannot do it only with html. You can define a function an use it like this:
<input type="text" id="myinputs" class="form-control" name="skills" placeholder="Enter skill(s), separate each with a comma" data-role="tagsinput"
onkeydown="letterOnly(event)"/>
function letterOnly(event) {
var key = event.keyCode;
return ((key >= 65 && key <= 90) || key == 8 || key == 32);// 8 for backspace and 32 for space
};
you can use the below regular expression to check letters, comma,
/^[A-Za-z,]$/;
$(document).ready(function() {
$('#myinputs').keyup(function(event){
var inputValue = event.charCode;
if (!/^[A-Za-z,]$/.test(event.item)) {
// set to true to prevent the item getting added
event.cancel = true;
}
});
});
And you must not bypass the point that,
There is no way to match an enter with a regular expression, since regular expressions are made to match string patterns, not keyboard input. (I know that is what you use it for, but still).
Your best bet would be to check the keycode of the special keys, before you check against the regular expression. The enter key is most likely keycode 13 (I havent checked, but you can easily check by printing the code to the screen).
This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 8 years ago.
I have these scripts...
Name: <input type="text" id="inputName" onblur="verifyName(this.value)">
<script type="text/javascript">
function verifyName(nameInput)
{
if(nameInput=="")
{
// error
alert('please enter your name');
}
else
{
// accepted
}
}
</script>
This will display an error if the user don't want to enter his/her name on the textbox.
What if the user is lazy and he/she will enter " " (a space or more) as a name? This can be accepted by the JavaScript. It will return false on the if condition.
But I want the user not to enter only spaces. Is there any way to do that?
Note: Any number of spaces (without any letters) inputted are invalid.
If the user inputs one of the texts below, JavaScript should accepts/rejects the input as follows...
"John" --> valid
"" --> invalid
"John Doe" --> valid
" " --> invalid
"John Doe" --> valid (can be edited to remove too many spaces)
" Kim" --> valid (can be edited to remove too many spaces)
" " --> invalid
function verifyName(nameInput)
{
nameInput = nameInput.trim();
if(nameInput=="")
{
// error
alert('please enter your name');
}
else
{
// accepted
}
}
The trim() function will remove all spaces. If there are only spaces in the var, trim() with return "".
Trim the string before you do the checking. See below
if(nameInput.trim()=="")
{
// error
alert('please enter your name');
}
else
{
// accepted
}
One (of quite a few) possible implementation of your function uses regular expressions:
function verifyName(nameInput) {
return input.match(/\w{1,12}/) === null ? false : true;
// ^^
// Or some other sensible limitation to the length of a name.
}
You can make use of regular expression to replace all the spaces from the string and then check its length. If there is at least one character remaining after removing all the spaces - that's your valid case right?
testInput = function(){
var inpStr = $('#txtInp').val();
var teststr = inpStr.replace(/\s/g, "");
//$('#testStrDiv').text(teststr);
if((teststr.length)&&(teststr.length>0))
{
$('#divOutp').html('<b>Valid! </b>');
}
else{
$('#divOutp').html('<b>Invalid! </b>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtInp" />
<input type="button" onclick="testInput()" value="test" />
<div id="testStrDiv" />
<div id="divOutp" />
Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".
You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.
You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/
Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).
Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/