I'm trying to apply Regular Expression Validation to a textbox User Control and it's only working when I enter something at the end of the text in the textbox. And when I type something somewhere in the middle of the text, it's not working.
For Example: Hey Man! (When I type '!' at the end of the text, my Code's working fine)
Hey! Man! (But when I insert '!' somewhere in the middle of the text after the entire text is typed, not working)
Below is my Code:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+$');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
Any help would be greatly appreciated! Thanks!
This should work. Your ending $ is what is keeping it from matching anything within the string:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
> Most simple code ....Special Characters Validation
function checkForm(theForm) {
var result = /^[a-z0-9\\.;,:'\\s]{1,100}$/i(theForm.data.value);
if (!result) {
alert("No legal characters entered");
}
return !!result;
}
Related
I'm working on a site where users can paste in embed codes from the likes of twitter, youtube, instagram, facebook, etc. The Embed code is validated and saved if valid.
The users can then see and edit the code and this is where some code fails validation. E.g. Twitter embed codes may contain < (aka '<') in the post name/text. When pasting in the code originally it passes validation as it contains <, but when displaying the code back to the user the browser shows < in the textarea and this is then submitted if the user clicks save. Our validation function treats this as the start of a tag and the validation fails.
Possible solution 1:
Better validation. The validation we use now looks like this It basically finds the tags (by looking for '<' etc) and checks that each open tag has a closing tag. There must be a better/standard/commonly used way:
(function($) {
$.validateEmbedCode = function(code) {
//validating
var input = code;
var tags = [];
$.each(input.split('\n'), function (i, line) {
$.each(line.match(/<[^>]*[^/]>/g) || [], function (j, tag) {
var matches = tag.match(/<\/?([a-z0-9]+)/i);
if (matches) {
tags.push({tag: tag, name: matches[1], line: i+1, closing: tag[1] == '/'});
}
});
});
if (tags.length == 0) {
return true;
}
var openTags = [];
var error = false;
var indent = 0;
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.closing) {
// This tag is a closing tag. Decide what to do accordingly.
var closingTag = tag;
if (isSelfClosingTag(closingTag.name)) {
continue;
}
if (openTags.length == 0) {
return false;
}
var openTag = openTags[openTags.length - 1];
if (closingTag.name != openTag.name) {
return false;
} else {
openTags.pop();
}
} else {
var openTag = tag;
if (isSelfClosingTag(openTag.name)) {
continue;
}
openTags.push(openTag);
}
}
if (openTags.length > 0) {
var openTag = openTags[openTags.length - 1];
return false;
}
return true
};
}
Possible solution 2:
Encode the text containing '<' (i.e. textLine.replace(/</g, '<')) without encoding tags like <blockquote class="...>.
I've been experimenting with something like:
$(widget.find("textarea[name='code']").val()).find('*')
.each(function(){
// validate $(this).text() here. Need to get text only line by
// line as some elements look like <p>some text <a ...>text
// </a>more text etc</p>
});
Possible solution 3:
Display < as < and not < in the browser/textarea. We use icanhaz for templating (much like moustache).
Using date.code = '<' with <textarea name="code">{{{code}}}</textarea> in the template does not work, neither does {{code}}.
So I played some more and the following works, but I am still interested in suggestions for better embed code validation or better answers.
After the edit form (inc textarea) code is created using the icanhaz template (i.e. after widget = ich.editEmbedWidgetTemplate(encoded_data);) I do the following to encode instances of < etc into < etc. ' has to be encoded manually using replace.
var embedCode = '';
$( widget.find("textarea[name='code']").val() )
.filter('*')
.each(function(){
embedCode += this.outerHTML.replace(/'/g, ''');
});
widget.find("textarea[name='code']").val(embedCode);
Why this isn't working?
I also did this by assigning the result back to the input field but that didn't work and still this is not showing an alert which should show the result..
<script type="text/javascript">
function calculate() {
var calculateit=document.getElementById('disp');
var pluscharacter=/+/;
var matchplus=calculateit.search(pluscharacter);
var inputlength=calculateit.length;
if(matchplus!=-1 && matchplus!=0 matchplus!=inputlength) {
answer=calculateit[0]+calculateit[1];
alert("Your answer is: "+answer+" Is it?");
}
}
</script>
Your if statement isn't a valid condition. Try:
if(matchplus!=-1 && matchplus!=0 && matchplus!=inputlength)
var calculateit = document.getElementById('disp');
var matchplus = calculateit.search(pluscharacter);
calculateit is a Node doesn't have any search() method.
You're doing stuff you don't need to do - just split the string. You also need to get the innerHTML - THAT's the string. Or you can get the "value" from an input field instead. I'd trim it to get rid of the white space around the equation, though the parseInt would take care of that as well. I'd also push the answer into another div. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/9ezky35v/2/
With this HTML:
<h3>Equation</h3>
<div id="disp">12+12</div>
<h3>Answer</h3>
<div id="answer"></div>
You can use this script:
function calculate() {
var calculateit = document.getElementById('disp').innerHTML.trim(),
numbers = calculateit.split('+'),
answerDiv = document.getElementById('answer');
if ( numbers.length > 1 ) {
answer = parseInt(numbers[0]) + parseInt(numbers[1]);
answerDiv.innerHTML = "Your answer is: <b>" + answer + "</b>, Right?";
} else {
answerDiv.innerHTML = "I can't calculate that equation.";
}
}
calculate();
I am using below code to validate hexadecimal numbers in a text box
$(document).ready(function () {
$('#vbus-id').keyup(function () {
var text_value = document.getElementById("vbus-id").value;
if (!text_value.match(/\b[0-9A-F]\b/gi)) {
document.getElementById("vbus-id").value = "";
// document.getElementById("vbus-id").focus();
var message = "You have entered a invalid id.Vbus id ranges from 0 to F in hexadecimal";
test.innerHTML = message;
}
});
});
If any numbers entered other than 0 to 9 and A to F it will clear the textbox and show a warning message below. But if I add a correct number after that, the warning mesage is not clearing. How to clear the warning message if I enter a valid entry after a wrong entry ?
jsFiddle
You've defined what happens if the form doesn't validate (set the message), but you also need the define what to happens in the opposite case (else):
$(document).ready(function () {
$('#vbus-id').keyup(function () {
var text_value = document.getElementById("vbus-id").value;
if (!text_value.match(/\b[0-9A-F]\b/gi)) {
document.getElementById("vbus-id").value = "";
// document.getElementById("vbus-id").focus();
var message = "You have entered a invalid id.Vbus id ranges from 0 to F in hexadecimal";
test.innerHTML = message;
} else test.innerHTML = '';
});
});
You could try always setting the message to blank first on keyup...
$('#vbus-id').keyup(function () {
test.innerHTML = "";
var text_value = document.getElementById("vbus-id").value;
...
I have this being created by my perl script.
print qq|
\$('textarea[name=category$row[0]]').keydown(function(event)
{
\$("input[value=$row[0]]").attr('checked', true);
});
|;
Somewhere later, I have this, I want to reextract the $row[0] value but I am not sure how in jquery.
print qq|
<script>
\$('#display_category').change(function() {
var text = \$(this).val();
\$('textarea[name^="category"]').each(function() {
var foundvalue = \$(this).val();
if (text == foundvalue)
{
alert("FOUND HERE " + foundvalue);
}
});
});
</script>
|;
how do i reextract the \d+ from category and use it in my if condition?
alert("category1234".match(/\d+/g)[0]);
So something like:
var num = $(this).attr('name').match(/\d+/g)[0];
or (I prefer this one):
var num = $(this).attr('name').replace(/[^\d]/g, '');
Demo: http://jsfiddle.net/karim79/8r8vs/3/
I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>