Javascript validation C#.NET - javascript

I am having a problem validating a textbox to not allow spacing. When the user enters a space I would like it to display an alert message and then clear the textbox, but the textbox doesn't clear. This is what I have so far.
function ValidateSpace () {
var SerNum = document.getElementById("txtbox1")
if (event.keyCode == 32) {
alert("This field may contain no spaces.");
document.getElementById ("txtbox1").value=""
}
}
I have users trying to put multiple entries in this space but it should only accept one. The textbox is for inventory purposes so it would change the nature of the data if I were to remove spaces

I suppose that you have to bind keyDown event on textbox
try this jquery code to remove live the spaces
$("#IdOfTheTextBox").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
If you can't use jquery try with this javascript function (onkeypress event of textbox)
function NoSpace() {
if (event.keyCode == 32) {
event.returnValue = false;
return false;
}
}
if you want to remove spaces after the input you can do this
var noSpaces = document.getElementById("txtbox1").value.replace(/\s/g, "");

Related

jQuery to prevent user from inputting if regular expression is not matched by using preventdefault

Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched
Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)
var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
$("#" + (idOfElement)).on("keyup",function (e) {
var val=this.value
var k = e.keyCode
if(k==46 ||(k > 48 && k <97)){
console.log(k)
return discountRegex.test(val);
}
});
in the above code idOfElement is the id i get on whichever field i focus.
Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.
<input type="text">
$(document).ready(function(){
$("input").bind('keypress', function(e) {
var str = e.keyCode;
if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
alert('Invalid')
e.preventDefault();
} else {
alert('Valid');
}
});
});
You can check if the regex is matched and if not you can remove the last char like the example below
I updated the code with keydown example
Example

Validate contenteditable on enter and not on clicking

I'm using contenteditable so as people can edit a text.
So when you edit the text thas has contenteditable = true, if you click somewhere else in the page, it will "validate" your text and replace the older.
That's not the comportment I'd like it to have because the user has no way to get back to the older text except by refreshing the page.
To me, it should validate the text only if you press the Enter Key and not if you click somewhere else. If you click somewhere else then it should get back to the older text.
Any idea how to make it ?
Thanks ! :)
When the user clicks the box, you can store its value into a var, and when they click away, reset the box to that var.
If the Enter key doesn't already validate, here's some pseudocode as to what you could do:
var oldvalue = "";
function OnClickBox() {
oldvalue = (yourelement).value;
}
function OnClickAway() {
(yourelement).value = oldvalue;
}
function Validate() {
(yourelement).value = yourvalidationfunction(yourelement.value);
}
document.onkeydown = function (e) {
key = e.which || e.KeyCode;
if (e.keyCode === 16) { //enter key
Validate();
}
}
Then you assign the box's onclick to OnClickBox(), and unselecting the box to OnClickAway().
And for future posts, please include some code as to what you have tried already, and for better context as to your question.

Lower word limit in textarea

I have this code, it displays word count and applies an upper word limit. Can you tell me how I can change this code to apply lower limit? For example if user enters 299 words and hits enter, a pop up should appear and say, you didn't enter enough words. Thanks.
$("#TextArea").on('keyup', function () {
var words = this.value.match(/\S+/g).length;
if (words > 300) {
var trimmed = $(this).val().split(/\s+/, 300).join(" ");
$(this).val(trimmed + " ");
}
else {
$('#display_count2').text(words);
$('#word_left2').text(300 - words);
}
});
});
You'll need to add a keypress event to have it work when enter is pressed. If you want it to work from anywhere in your form, you could add it on the document. That way it will be run no matter where enter is pressed.
$(document).keypress(function(e) {
if(e.which == 13) {
checkWordLimit();
}
});
You could then hook this up to a function that checks the word length
function checkWordLimit() {
var words = this.value.match(/\S+/g).length;
if (words < 300) {
alert("You need to enter at least 300 words!");
} else {
$('#display_count2').text(words);
$('#word_left2').text(300 - words);
}
}
If you want to keep the word count text updated, then just keep calling that function in the keyup event:
$("#TextArea").on('keyup', function () {
checkWordLimit();
});
To have it check before it submits the form (on a button click), then you can change the function to return true/false based on the word count check, and then submit the form if it is successful. Note that this is for a regular button, not a submit button. If it's a submit button, then the submit event in the form will need to be intercepted.
$("#SomeButton").on('click', function () {
if(checkWordLimit()) {
$("#SomeForm").submit();
}
});
You need to add keydown event on that text area, and your event handler function should be something like this.
function onKeyDown(e){
if(e.keyCode == 13){ //for enterkey
var words = this.value.match(/\S+/g).length;
if(words >= 300){
//Your success code
}else{
alert("You didn't enter enough words");
}
}
}

Prevent From Writing on TextArea using Bind Event "input propertychange"

I am handling the content inside a textarea using binding a function to the event "input propertychange"
Like this:
$('#textarea').bind('input propertychange', function () {
var textarea = document.getElementById('textarea');
window.lastLineWriting = textarea.value.substr(0, textarea.value.length).split("\n").length;
var writingOnLine = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
if (writingOnLine < window.lastLineWriting) {
//dont write on textarea
}
});
I don't know how to prevent the char typed by the user's keyboard to appear on the textarea... Inside that if I want to prevent the text to be inserted on textarea..
How can I do this?
you could easily stop the user from typing with this code, using jQuery:
$('textarea').bind('keypress', function (e) {
e.preventDefault();
return false;
});
NOTE:
this code will prevent the user from typing in all the textareas, to bind it specifically to one or some selected elements, you must change the selector to the desired elements.
var editable = false // Your Condition
if(editable != "true"){
$("#textarea" ).attr("disabled",true);
}

Detect when text is entered into the textarea and change it correspondingly

I have a textarea where users can enter or paste email addresses of other people and send them an invite after pressing Submit button. Each email must be seperated with a comma and valid before the form is submitted - validation is taken care of by jQuery Validate plugin & multiemail method.
Problem
Some people paste email addresses directly from their email clients and those emails are often in a weird format - containing name and surname before the actual email, or the email is wrapped in < >. For example:
"The Dude" <the.dude#gmail.com>, "The Dudette" <thedudette193#gmail.com>
Question
What I want to do is to Extract all email addresses from bulk text using jquery, but I'm having problems integrating this piece of code to work with my textarea - I don't know where to start.
How could I use the code from the above answer to extract each email entered into the textarea after a comma is typed or when the focus is moved away from textarea? So if I paste "The Dude" <the.dude#gmail.com> and type , after it or switch focus away, the entered value would change to the.dude#gmail.com.
I'm guessing something like this :
var textarea = $('#emails');
textarea.on({
keyup: function(e) {
if (e.which === 188) check();
},
blur: check
});
function check() {
var val = $.trim(textarea.val()),
err = '';
if (!val.length) {
err = 'No input ?';
return;
}
var emails = val.split(','),
notvalid = [],
temp = [];
$.each(emails, function(_,mail) {
mail = $.trim(mail);
if ( mail.length ) {
var m = mail.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
if (m) {
temp.push(m);
}else{
temp.push(mail);
notvalid.push(mail)
}
}else{
temp.push(mail);
}
if (notvalid.length) err = 'Not valid emails : ' + notvalid.join(', ');
});
$('#error').html(err);
textarea.val((temp.length ? temp : emails).join(', '));
}
FIDDLE
you can detect when an textarea is changed (or other input field) by using an eventhandler. Jquery supports multiple events (have a look here http://api.jquery.com/category/events/). In this particular case I should use the keyup event for triggering the extractEmails function. This way your extraction will be "live". However, it is also possible by catching a blur or change event.
With keyup eventhandler
http://jsfiddle.net/kasperfish/9hLtW/5/
$('#text').on('keyup',function(event) {
emails=extractEmails($(this).val());
$("#emails").text(emails);
});
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
This will convert the entered text to emails when you either lose focus, or enter a comma, as you requested:
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
$("#emailtext").on('keypress blur', function(e) {
if (e.which === 44 || e.type =="blur")
{
$('#emails').text(extractEmails($("#emailtext").val()));
}
});
Here's the fiddle:
http://jsfiddle.net/Mj2KM/

Categories