Issue in regular expression - javascript

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');
}
}

Related

How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?

enter image description here
How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?
You can check if the character of the string is uppercase by comparing the ASCII code. If it's between 65 & 90, the character is in uppercase.
Then by applying toUpperCase & toLowerCase methods will transform uppercase alphabets into lowercase and vice-versa.
function isUpperCase(c) {
return c >= 65 && c <= 90;
}
var string = "AaBbCcDd *+-";
var updatedString = string.split("").map(c => isUpperCase(c.charCodeAt(0)) ? c.toLowerCase() : c.toUpperCase()).join("");
console.log("Original String:: " + string);
console.log("Transformed String:: " + updatedString);
You can use this code alternate character
function alternate(changeString) {
var charArray = changeString.toLowerCase().split("");
for (var i = 1; i < charArray.length; i += 2) {
charArray[i] = charArray[i].toUpperCase();
}
return charArray.join("");
};
var text = "Test";
console.log(alternate(text));
For the transformation, you can use the following:
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
}
A complete example here: (although it isn't exact the same that is in your pic)
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
return result;
}
$('#text').on('input', function(){
$('#display').val(convert(this.value));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>input</label><input id="text" />
<label>display</label><input id="display" disabled />
Please refer below code may be it will help you,
Keyup event will work each character
$(document).ready(function(){
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
$("#text").keyup(function(){
var l =this.value.length;
var s =this.value;
var r =new Array();
for(var i=0;i<l;i++){
if(upperCase.test(s[i])){
r.push(s[i].toString().toLowerCase());
}
if(lowerCase.test(s[i])){
r.push(s[i].toString().toUpperCase());
}
}
$("#res").val(r.toString().replace(/\,/g, '').trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<br>
Result:<input type="text" id="res">

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

Reverse case (Lowercase/Uppercase) of an input value character by character

By using one input text box and the input type allows only alphabets.The value entered is 'a' and it should be display outside the textbox as 'A'?
If we enter the alphabet small 'a' on input text then it will wanted to display capital 'A' on the outside of the box...
The following is my html code:
<!DOCTYPE html>
<html>
<head>
<!--<script type="text/javascript" href="check.js"></script>-->
</head>
<body>
<input type="text">
<script>
function myFunction()
{
var A = document.getElementById('input').value;
console.log('alphabet'.toUpperCase());
}
</script>
</body>
</html>
To show the input value with case reversed you should:
Call your function in the onkeyup event of your input to update the preview immediately with the inputted string.
And loop through your string and for each character test if it's in
uppercase reverse it to lowercase or make it uppercase if it's
lowercase.
Here's a Snippet DEMO:
function myFunction() {
var A = document.getElementById('input').value;
var output = '';
for (var i = 0, len = A.length; i < len; i++) {
var character = A[i];
if (character == character.toLowerCase()) {
// The character is lowercase
output = output + character.toUpperCase();
} else {
// The character is uppercase
output = output + character.toLowerCase();
}
}
document.getElementById("preview").innerText = output;
}
<input id="input" type="text" pattern="[A-Za-z]" onkeyup="myFunction()" /><span id="preview"></span>
You may use an event for immediatly update the result, while writing.
document.getElementById('input').addEventListener('keyup', function () {
var input = document.getElementById('input').value;
if (!input.match(/^[a-z]*$/i)) {
document.getElementById('output').innerHTML = 'Wrong input';
return;
}
document.getElementById('output').innerHTML = input.split('').map(function (a) {
return a.match(/[a-z]/) ? a.toUpperCase() : a.toLowerCase();
}).join('');
});
<input type="text" id="input">
<div id="output"></div>
function reverseCase(str) {
let newstr = str.split('');
let newarr = [];
//return newstr;
for(i=0; i<newstr.length; i++) {
if(newstr[i] == newstr[i].toLowerCase()){
newarr.push(newstr[i].toUpperCase());
}else
if(newstr[i] == newstr[i].toUpperCase()){
newarr.push(newstr[i].toLowerCase());
}
} return newarr.join('');
}
console.log(reverseCase("Happy Birthday"))

Disallow special characters in textbox validation

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>

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.");
}
});
});

Categories

Resources