Javascript function For Alpha Numeric in Asp.net [duplicate] - javascript

I have a textbox, and it needs not allow the user to enter any special characters. He can enter:
A-Z
a-z
0-9
Space.
One more condition is the first letter should be alphabetic.
How can I do a JavaScript verification on each keypress?

add a onKeyUp="javascript:checkChar(this);" to the input box.
function checkChar(tBox) {
var curVal = tBox.value;
if ( /[^A-Za-z0-9 ]/.test(curVal) ) {
//do something because he fails input test.
}
}
alernatively to check JUST the key that was pressed you can grab the keycode from the event like so:
onKeyUp="javascript:checkChar(event);"
function checkChar(e) {
var key;
if (e.keyCode) key = e.keyCode;
else if (e.which) key = e.which;
if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) {
//fails test
}
}
missed the part about first char, but you can do a test on the textbox value as in the first example:
/^[A-Za-z]/.test(curVal)
or even use the second method but pass the text box as well so you can get it's full value.

This function will check the string given to it for those criteria:
function checkvalue(value) {
return value.match( /[A-Za-z][A-Za-z0-9 ]*/ );
}
You can then use that in an onkeypress event, passing in the current value.

Now that we have HTML5, you don't even need to use JavaScript. You can use the pattern attribute.
<input type="text" pattern="[A-Za-z][A-Za-z0-9 ]*" title="Description of format" />
The pattern attribute should contain a regular expression defining the format. And title should contain a human-readable description of the format.
Then on validation, depending on the browser, the browser will outline the field in red and/or display a message stating your description of the format.
This tutorial goes into more detail: HTML5 Input Validation Tutorial.

You should check pressed key in onkeydown event handler of the textbox and if it doesn't conform conditions then return false from the handler. Using keyup will not allow you to prevent char from being actually inputted in the textbox.

I don't think you should check on each keypress, it could be very annoying for the user.
Just check the input when it loses the focus, or when submiting.
To do it, you can use a regex and use this pattern:
`/[a-z]{1}[a-z0-9]/i`
You can also take a look at the JQuery Validation Plugin

Related

Restrict Exponents and periods(.) in numeric textbox html

I have a numeric textbox, by default numeric textbox allows Exponents and periods.
How do i restrict that?
One of the method i can think of is using string.replace on input event however it is not working as expected. Below is my code..
HTML
<input type='number' class='number'>
JavaScript
$(".number").on('input', function () {
this.value = this.value.replace(/e|E|\./g, ''); // Remove e, E, and period(.)
if (this.value.length > 4) {
this.value = this.value.slice(0, 4);
}
});
When i enter string '2e' in textbox, entire input is getting removed if above code is ran. i just wants to remove e, E or period from input string not entire input.
Is there a way to achieve this.
JSfiddle
Answer BY nichel is working like a charm, now my problem is how do i restrict the same in PASTE event.?
So basically you want to allow just numbers? Then restrict the keys by keycode & remove excess chars on paste
$(".number").keypress(function(e){
return e.keyCode>47&&e.keyCode<58;
}).paste(function(){
$(this).val($(this).val().replace(/\D/g,''));
})
And since you'd like the max length to be 4, just add max="9999":
<input type='number' class='number' max="9999">
input[type=number] returns ""(blank string) if input value is not valid.
You can refer this post for more information.
I would suggest you to use input[type=tel] instead. It also has a maxLength attribute so you so not have to worry about trimming extra values.
You can even replace your regex to /[^0-9]/. This will replace all characters except numbers.
Sample Fiddle.
So you final code would look like: JSFiddle

How to disable/remove only first space on input field?

Good morning everybody!
I have a case, when I should prevent users to entering space as a first character on input field.
I have a demo here: http://jsbin.com/foyetolo/2/edit
It works only when you hit spacebar for first time. When you start typing other characters and select whole text in input (ctrl+a) and then hit the space bar it adds the space in the beginning of input field.
So, how to check if on keypress/keydown if the first character will be a space, return false and not allow it to type the space as a first character?
You can do this by checking if key is space and selection start is 0 as below:
$(function() {
$('body').on('keydown', '#test', function(e) {
console.log(this.value);
if (e.which === 32 && e.target.selectionStart === 0) {
return false;
}
});
});
Demo Link
This jQuery function selects all the text inputs when a key is unpressed, removes all whitespace from the beginning of the string and replaces the value of the input:
<script>
$(":text").keyup(function () {
$(this).val($(this).val().replace(/^\s+/,""));
}
</script>
I do not recommend to use trim() when blank spaces are replaced directly with keyup() because when you type a space after a word, it will be deleted before you start writing the next word.
Try something like
$('input').keyup(function () {
if($(this).val() == '') {
if(event.keyCode == 32) {
return false;
}
}
}
This would check for current value, and then it would run the function. Keyup is used, to check for the value after the key has been unpressed. If you use keydown, it would still have the value. Key up would get the value after the key press event has passed.
Or as others has told you to always keep trimming the value. You can use jQuery trim() method to trim the value, regardless of whether user inputs space character or not.
$('input').keyup(function () {
$(this).val($.trim($(this).val()));
}
This would add the trimmered form of the value of the current input field.
document.querySelector('#test').addEventListener('input',function(e){
if(e.target.value===" ")
e.target.value="" })
this code dosent let users space at the first even if any users select
whole text in input (ctrl+a) and then hit the space bar

jquery to read and compare a word as you type

I need to implement a sort of word sensing feature . What I require is to have a plugin which will read and compare a word, as I type , with a predefined word , and on successfull matches , it will display a checkbox .
As in the image , once I type test and give a space , it will take the entire word Test and compare it with a predefined word say "Testimony" . Now, as I have given a space after Test , it won't match with the reference word and it will wait for the next word. Again , as a user presses spacebar , it will take the new word and start comparing .
If you need a more customizable option than jQuery's autocomplete, you can bind a keypress event to the textbox you are typing in, check the keycode of the key that the user is pressing, and act accordingly. Something along the lines of this:
$('#textarea').bind('keypress', function(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
if( key == '32') {
alert("spacebar was pressed");
var input = $("#textArea").val();
// Put your comparison logic here
}
});
I remember there being some funkiness with how IE handles codes, but the above works at least with FF and Chrome.

Detecting whether user input contains a forbidden character in JavaScript

I have a text box that is going to be validated in JavaScript upon click on the submit button.
Only the character 0-9 and a-f and A-F are allowed.
So g-z and G-Z as well as other characters such as punctuation or not allowed.
The code I have so far is:
function validate_form ( )
{
valid = true;
if ( document.form.input.value == [a-zA-Z_,.:\|] )
{
alert ( "You can only enter either 0-9 or A-F. Please try again." );
valid = false;
}
return valid;
}
Which doesn't seem to work.
I'm new to JavaScript so can any one please give me a hint as to where I'm going wrong?
We can actually clean this code up a lot. There's no need to keep track of valid as test() will provide us with the true or false value we're looking for. It's also a good deal easier in your case to keep a whitelist of acceptable characters rather than a blacklist. That is, we know every character we want, but can't possibly specify every character we don't want.
function validate_form() {
return /^[a-fA-F0-9]+$/.test(document.form.input.value);
}
Note that you can also use this to do a pre-check:
document.form.input.onkeyup = function() {
if (!validate_form()) {
alert("You can only enter either 0-9 or A-F. Please try again.");
}
};
the syntax is /^[a-zA-Z_,.:\|]+$/.test(document.form.input.value). Notice the ^ and $: without them, the test will pass even for strings that have only at least one allowed character.
The best way for validation is to not let the user, enter wrong character. Use this code (this is the jQuery version, but you can also convert it easily to JavaScript):
$('#inputFiledId').keyup(function(e){
// checking the e.keyCode here, if it's not acceptable, the return false (which prevents the character from being entered into the input box), otherwise do nothing here.
});
This is called pre-check. Please consider that you whatever you do in client-side, you should always check the values at the server also (have server-side validation) as there are multiple hacks around, like form-spoofing.
You could do something like this
$('input').keyup(function(){
var charac = /[g-zG-Z;:,.|_]/;
var result = charac.test($(this).val());
if(result == true){
alert('You can only enter either 0-9 or A-F. Please try again.');
}
})
http://jsfiddle.net/jasongennaro/GTQPv/1/

Disabling some special characters in text area

Hey guys, I'm thinking of ways to disable users from typing some special characters like < and >. But I would like them to use full stops and commas and question marks and exclamation marks and quotes. I've come up with this piece of code but it doesn't seem to allow any special character.:
<script type="text/JavaScript">
function valid(f) {
!(/^[A-zÑñ0-9]*$/i).test(f.value)?f.value = f.value.replace(/[^A-zÑñ0-9]/ig,''):null;
}
</script>
There are several ways of doing this, none of them are a good way to go tho, but we'll get to that.
you can bind to onkeyup/onkeydown/onkeypress events on the element and cancel events for characters you have blacklisted. This will not stop people from pasting the characters into the field however.
You can bind to the onchange event of the element and them remove the blacklisted characters from it, once the user is done inputting.
The problem with any type of sanitizing like this in javascript is that it is trivial for a user with a tiny bit of knowhow, to circumvent these measures and still upload the offending characters to the server anyway.
So if you don't want to allow special characters in the user generated input you should either
remove them serverside after the userinput has been submitted
keep them but encode them into html entities > and < for > and < for instance before outputting them anywhere on your webpage.
Try with this...
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.formname.fieldname.value.length; i++) {
if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
why not simply check the character pressed on "onKeyDown" event?
<textarea id="foo"></textarea>
<script>
document.getElementById('foo').onkeydown = validate;
function validate(){
var evtobj = window.event? event : e; // IE event or normal event
var unicode = evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey = String.fromCharCode(unicode);
]
return (/^[A-zÑñ0-9]*$/i).test(actualKey);
</script>
This simply gets the key which was pressed, and if it is a valid one returns true, otherwise false, this, in term, determines if the key is actually written in the textarea or not

Categories

Resources