Disallow special characters in textbox validation - javascript

I have javascript code where the validation does not allow more than 20 characters in text box. But, I also want to disallow in special characters in the validation; how can this be accomplished.
Here is my current validation code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js">
/script>
<script type='text/javascript'>
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var len = desc.length;
if (desc.length >= 10)
{
this.value = this.value.substring(0, 10);
} $('#spntxt').text(10 - len + ' Characters Left');
});
}); </script>

try bellow script this will not allow special charter # $ % ^ & * ( )
function validate() {
var element = document.getElementById('input-field');
element.value = element.value.replace(/[^a-zA-Z0-9#]+/, '');
};
<input type="text" id="input-field" onkeyup="validate();"/>

I just use your codes and modify:
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var lastChar = desc.slice(-1);
var spc = !((lastChar.charCodeAt()>=48&&lastChar.charCodeAt()<=57)||(lastChar.charCodeAt()>=65&&lastChar.charCodeAt()<=90)||(lastChar.charCodeAt()>=97&&lastChar.charCodeAt()<=122));
if (desc.length >= 10 || spc)
{
this.value = this.value.substring(0, desc.length-1);
} $('#spntxt').text(10 - len + ' Characters Left');
});
});

You must use the keypress event
<input type="text" onkeypress="return isValidCharacter(event)" />
and define the javascript event, the validation can do it with regular expressions
function isValidCharacter(e) {
var key;
document.all ? key = e.keyCode : key = e.which;
var pressedCharacter = String.fromCharCode(e)
var regExp = /^[a-zA-ZÁÉÍÓÚáéñíóú ]*$/;
return regExp.test(pressedCharacter); }
If the method returns true the character will be printed

For Input Length, use Html5 Max Length Property
$(function(){
$('#QI4562040').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
$('#spntxt').text(10 - input_val.length + ' Characters Left');
});
});
<input type='text' name='' id='QI4562040' maxlength='10'/>
<div id='spntxt'></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

Related

Jquery:Registration Number Validation on Keypress

I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>

Issue in regular expression

In the below code i have a textbox in which when i enter numeric it should alert that only alphabets are allowed.In which i get the regular expresion and spilt it and store in an array and for loop it and check the regular expression that i enter in my textbox.Pls help to solve the issue.
<input type="text" id="check" onblur="validate()" />
<script type="text/javascript">
function validate() {
var hiddenValue = new RegExp( "[A-Z]~~[a-z]");
// var val = document.getElementById("check").value;
var mySplitResult = new Array();
mySplitResult = hiddenValue.split("~~");
for (i = 0; i < mySplitResult.length; i++) {
document.write("<br /> Array[" + i + " ]= " + mySplitResult[i]);
if (mySplitResult.test(document.getElementById("check").value)) {
alert('check');
return false;
}
}
}
</script>
If you want to test that an input is all letters:
if (!document.getElementById("check").value.test(/^[a-z]+$/i)) {
alert ("Only letters are permitted");
return false;
}
See this fiddle. Will check that only letters are in the textbox otherwise alert.
http://jsfiddle.net/2EDYV/2/
function validate() {
var result = /^([a-zA-Z]+)$/.test(document.getElementById("check").value);
if (!result) {
alert('numeric value found');
}
}

Count textarea characters

I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
$(document).ready(function() {
var tel1 = document.forms["form"].elements.tel1;
var tel2 = document.forms["form"].elements.tel2;
var textarea = document.forms["form"].elements.textarea;
var clock = document.getElementById("clock");
var count = document.getElementById("count");
tel1.addEventListener("keyup", function (e){
checkTel(tel1.value, tel2);
});
tel2.addEventListener("keyup", function (e){
checkTel(tel2.value, tel3);
});
/*$("#textarea").keyup(function(){
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
console.log("Characters left: " + charactersLeft);
});​*/
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});
function checkTel(input, nextField) {
if (input.length == 3) {
nextField.focus();
} else if (input.length > 0) {
clock.style.display = "block";
}
}
function textareaLengthCheck(textarea) {
var length = textarea.length;
var charactersLeft = 500 - length;
count.innerHTML = "Characters left: " + charactersLeft;
}
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks #Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
⚠️ The accepted solution is outdated.
Here are two scenarios where the keyup event will not get fired:
The user drags text into the textarea.
The user copy-paste text in the textarea with a right click (contextual menu).
Use the HTML5 input event instead for a more robust solution:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Here is simple code. Hope it help you
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>
I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.
$(function() {
$("#myTextArea").on("input propertychange", function(event) {
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
$("#counter").html(curlen);
});
});
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />
For those wanting a simple solution without jQuery, here's a way.
textarea and message container to put in your form:
<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>
JavaScript:
<script>
function count_it() {
document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>
The script counts the characters initially and then for every keystroke and puts the number in the counter span.
Martin
They say IE has issues with the input event but other than that, the solution is rather straightforward.
ta = document.querySelector("textarea");
count = document.querySelector("label");
ta.addEventListener("input", function (e) {
count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>
var maxchar = 10;
$('#message').after('<span id="count" class="counter"></span>');
$('#count').html(maxchar+' of '+maxchar);
$('#message').attr('maxlength', maxchar);
$('#message').parent().addClass('wrap-text');
$('#message').on("keydown", function(e){
var len = $('#message').val().length;
if (len >= maxchar && e.keyCode != 8)
e.preventDefault();
else if(len <= maxchar && e.keyCode == 8){
if(len <= maxchar && len != 0)
$('#count').html(maxchar+' of '+(maxchar - len +1));
else if(len == 0)
$('#count').html(maxchar+' of '+(maxchar - len));
}else
$('#count').html(maxchar+' of '+(maxchar - len-1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="message" name="text"></textarea>
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
This solution will respond to keyboard and mouse events, and apply to initial text.
$(document).ready(function () {
$('textarea').bind('input propertychange', function () {
atualizaTextoContador($(this));
});
$('textarea').each(function () {
atualizaTextoContador($(this));
});
});
function atualizaTextoContador(textarea) {
var spanContador = textarea.next('span.contador');
var maxlength = textarea.attr('maxlength');
if (!spanContador || !maxlength)
return;
var numCaracteres = textarea.val().length;
spanContador.html(numCaracteres + ' / ' + maxlength);
}
span.contador {
display: block;
margin-top: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>

Using Regex to limit special characters in a textbox using jquery in ASP.net MVC form

I'm trying to limit to 3 the number of special characters in a text box using JQuery. The special characters can be in any order and can be adjacent to each other or scattered over the length of the text box. I spent the last 24 hours reading almost all relevant posts in stackoverflow and trying the suggestions.
I still haven't come with a suitable regex.
Here is what I have so far at the bottom of my ASP.net mvc form:
<script type="text/javascript">
$(document).ready(function () {
$('input[id$=textbox1]').bind('blur', function () {
var match = /^[.,:;!?€¥£¢$-~#%&*()_]{4,50}$/g.test(this.value);
if (match == true)
alert("Please enter a maximum of 3 special characters.");
});
});
</script>
Below is the list of special characters I'm targeting:
~`!##%^&*()-_:;?€¥£¢$-~{}[]<>/+|=
You where thinking to difficullty. Just count how often the elements are inside the input and throw a warning when the count is over three.
here is an
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="jquery-1.8.3.min.js"></script>
<script>
var limitchars = '[~`!##%\^&\*\(\)-_:;\?€¥£¢\${}\[]<>/+\|=]'
$(function () {
var teststring = "~`!##%\^&\*\(\)-_:;\?€¥£¢\${}\[]<>/+\|='-:;";
var regex = /[~`'!##%\^&\*\(\)-_:;\?€¥£¢\${}\[\]<>/+\|=]/g
//var test1 = teststring.match(regex);
//debugger;
//alert(teststring.length === test1.length);
$('input').keyup(function () {
var text = this.value;
var match = text.match(regex);
if (match.length > 3) {
alert('invalidI input');
}
});
});
</script>
</head>
<body>
<input type="text" />
</body>
</html>
Don't forget to escape the regular expression (http://www.regular-expressions.info/reference.html ). The g at the end of the regex counts the number of occurrence in string (http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string )
You can find the number of bad characters by counting the number of matches.
Working example at http://jsbin.com/alidus/1/
$(document).ready(function () {
$('#test').bind('blur', function () {
var charactersToExlude = "~`!##%^&*()-_:;?€¥£¢$-~{}[]<>/+|=";
var badCharacterRegex = "[" + charactersToExlude.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + "]";
console.log(badCharacterRegex);
var patt=new RegExp(badCharacterRegex, "g");
var matches = this.value.match(patt);
var numberOfBadCharacters = matches ? matches.length : 0;
if (numberOfBadCharacters >= 3) {
$("#result").text("Please enter a maximum of 3 special characters. (" + numberOfBadCharacters + " bad characters).");
} else {
$("#result").text(numberOfBadCharacters + " bad characters.");
}
});
});
First we escape any bad characters that have meaning to regex. Then crete the pattern, match it, if any matches, count the number of matches.
$(document).ready(function () {
$('#test').bind('blur', function () {
var charactersToExlude = "~`!##%^&*()-_:;?€¥£¢$-~{}[]<>/+|=";
var badCharacterRegex = "[" + charactersToExlude.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + "]";
console.log(badCharacterRegex);
var patt=new RegExp(badCharacterRegex, "g");
var matches = this.value.match(patt);
var numberOfBadCharacters = matches ? matches.length : 0;
if (numberOfBadCharacters >= 3) {
$("#result").text("Please enter a maximum of 3 special characters. (" + numberOfBadCharacters + " bad characters).");
} else {
$("#result").text(numberOfBadCharacters + " bad characters.");
}
});
});

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources