I want to prevent the use of "," and ";" on an input field with Jquery. I have been trying this solution so far:
HTML :
<input name="txt_correu-e" type="text" id="gestio_usuaris_editaCompta_txt_correu-e" size="50" maxlength="50" class="">
JQUERY:
$('#gestio_usuaris_editaCompta_txt_correu-e').keypress(function (e) {
var filter = /([,;])/;
var campo = $("#gestio_usuaris_editaCompta_txt_correu-e").val();
if (filter.test(campo)) {
e.preventDefault();
}
});
But is not working for me since the input still print the character and then won't let me continue writting in the input. I just want the input to not show those characters but let me continue writting the email adress.
To prevent the user to type , and ;, you can simply do :
$("#target").keypress(function( event ) {
if ( event.which == 44 || event.which == 59 ) {
event.preventDefault();
}
// other instructions
});
Edit :
To validate an email address, you can use :
function is_valid_email(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
which you can call in any needed event ( keyup, ... ) on your text field.
You can also use the HTML5 email input :
<form>
E-mail: <input type="email" name="email">
</form>
Hope that can help.
Like I said in my comment, there's no need to use jQuery or JavaScript to do this, and restricting an input through the keyPress event is not a good practice, since anyone can copy and paste the content (not even with "evil" intentions).
The following solution would allow any characters except for "," and ";". Keep in mind this is not enough to ensure an email address is valid, of course.
<form>
<input type="text" pattern="^[^,;]*$" required/>
<input type="submit">
</form>
http://jsfiddle.net/parvmck7/
Let me know if you have doubts.
UPDATE: I didn't realise you needed this to be compatible with IE8. If this is the case, you can try with any of the HTML5 Polyfills (https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#web-forms). Otherwise, JavaScript will be.
$("#target").on('keyup click blur',function( event ) {
var regex = new RegExp('^([A-Z0-9_.+-])+\#(([A-Z0-9-])+\.)+([A-Z0-9]{2,4})+$/', 'i');
if(!regex.exec($(this).val())){
$(this).val("");
event.preventDefault();
});
In order to avoid the insertion of unwanted characters you should listen to keyup event(keyboard), click event( to prevent right click and paste ;:-containing text) and blur event(if the input has been selected via TAB key in order to paste ;:-containing text).
For other mail-validation polices pls see regular-expressions.info
Related
I am trying to add a newline on pressing enter key, but \n is not working here. \t is working, as is anything except \n.
This code prevents the submitting of the form on pressing the enter key, but doesn't add a newline to the text:
<script src="jquery-3.2.1.min.js">
$(document).ready(function(){
$('#text').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
var s = $(this).val();
$(this).val(s+"\n");
}
});
});
</script>
<input type="text" id="text" name="post">
<input type="submit" value="Post">
Would it make more sense for you to use a textarea?
https://www.w3schools.com/tags/tag_textarea.asp
This will prevent submitting the form but also allow you to enter new lines.
As far as I know, you can't make new lines in an input.
use <textarea name="Text1" cols="40" rows="5"></textarea> and change the rows value using js.
It is better to use <textarea rows='20' cols="20"></textarea>.
Set the values of cols and rows accordingly to your need.
<input type="text" name="dmeo">
The above line is only useful when we are getting any short data like name, surname, username, etc.
If we are talking about which one is better then we have to be more specific about it application that where we gonna use it. If we are talking about any input field that is used to get data regarding form submission or if we want different types such as submit/radio-button, checkbox or any hidden type then we can use input tag. But if we are talking about accepting any detailed information(address, description of an product, etc..) from the user then textarea is much more preferable. We can also predefine numbers of rows and cols attributes, or even better; through CSS' height and width properties
To disable form submit on enter btn
$("#regForm").keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
but the code above will disable enter btn on the entire form field use this on textarea for new line
$('#text').keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
var s = $(this).val();
$(this).val(s + "\n");
}
});
I have a form where a user will set up a new Username. The issue is user's have been creating username's with a space and I want to avoid that.
I have been able to detect when there is a space using the following:
var hasSpace = $('#usernameValue').val().indexOf(' ')>=0;
However I cannot figure out to have the form check for that space when the user is typing in that input section.
How would I change my code to do this?
Thank you!
As suggested you can use the keyup function. This example checks if you entered space and alerts the user
$('#usernameValue').keyup(function(e) {
if (e.which === 32) {
alert('you entered space');
// Do whatever logic is needed here
}
});
Working JsFiddle
Are you using an input tag?
If so, you can use the pattern attribute to define a regular expression that doesn't accept whitespaces. For example:
<input type="text" name="username" pattern="/^\S*$/">
For more information: https://www.w3schools.com/tags/att_input_pattern.asp.
Using onkeyup event.
input.onkeyup = function(){
var hasSpace = $('#usernameValue').val().indexOf(' ')>=0;
}
Is there a possiblity to force an iOS-device to show the numeric keyboard while using a custom pattern as input type?
my input pattern:
<input id="price" class="numeric" pattern="\d+((\.|,)\d{1,2})?" name="price"
title="" data-mini="true" data-clear-btn="true" autocomplete="off" autofocus />
I want to type a currency value like '14.99' and show up a keyboard with access to numbers on the iOS device
<input type='number' />
<input pattern='[0-9]*' />
<input pattern='[\d]*' />
are all missing the decimal sign and/or are not validating as number when adding a decimal sign. An alternative way could be a javascript function which is creating the decimal sign on the right place, like pressing 1->2->9->9 in this order creates on keypress() 0.01->0.12->1.29->12.99,
but this requires the input field to be type='text' --> obvious problem here is that the text keyboard is showed when focussing the input field.
How can I solve this issue?
EDIT
Environment:
JQM 1.3.2
jquery 1.8.2
For now, JavaScript is the only solution. Here's the simplest way to do it (using jQuery):
HTML
<input type="text">
JavaScript
$('input[type="text"]').on('touchstart', function() {
$(this).attr('type', 'number');
});
$('input[type="text"]').on('keydown blur', function() {
$(this).attr('type', 'text');
});
The idea is simple. The input starts off and ends up with type="text", but it briefly becomes type="number" on the touchstart event. This causes the correct iOS keyboard to appear. As soon as the user begins to enter any input or leave the field, the input becomes type="text" once again, thus circumventing the validation.
There's one downside to this method. When the user returns to an input that has already been filled out, the input will be lost (if it doesn't validate). This means the user won't be able to go back and edit previous fields. In my case, this isn't all that bad because the user may want to use the calculator over and over again with different values, so automatically deleting the input will save them a few steps. However, this may not be ideal in all cases.
It looks like Mobile Safari supports the new HTML5 input type attributes of email, number, search, tel, and url. These will switch the keyboard that is displayed. See the type attribute.
So for example, you could do this:
<input type="number" />
And when the input box has focus, the number keyboard is shown (as if the user had the full keyboard and hit the "123" button.
If you really only want numbers, you could specify:
<input type="tel" />
And then the user would get the phone number dialing keypad.
I know this works with Mobile Safari -- I only assume it will work with UIWebView.
http://conecode.com/news/2011/12/mobile-safari-uiwebview-input-types/
I made this little snippet to achieve what you want and I've tested it on iPhone 5 v7.0.3
I used e.which to read CharCode entered and then push it into an array (before) which represents digits before decimal mark and another array (after) to move values from (before) array past the decimal mark.
It might look complicated, due to my humble programming skills.
1) Code demo - 2) Currency conversion demo
HTML:
<input type="tel" id="number" />
JS
Variables and functions:
// declare variables
var i = 0,
before = [],
after = [],
value = [],
number = '';
// reset all values
function resetVal() {
i = 0;
before = [];
after = [];
value = [];
number = '';
$("#number").val("");
$(".amount").html("");
}
// add thousand separater
function addComma(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Main code:
// listen to keyup event
$("#number").on("keyup", function (e, v) {
// accept numbers only (0-9)
if ((e.which >= 48) && (e.which <= 57)) {
// convert CharCode into a number
number = String.fromCharCode(e.which);
// hide value in input
$(this).val("");
// main array which holds all numbers
value.push(number);
// array of numbers before decimal mark
before.push(value[i]);
// move numbers past decimal mark
if (i > 1) {
after.push(value[i - 2]);
before.splice(0, 1);
}
// final value
var val_final = after.join("") + "." + before.join("");
// show value separated by comma(s)
$(this).val(addComma(val_final));
// update counter
i++;
// for demo
$(".amount").html(" " + $(this).val());
} else {
// reset values
resetVal();
}
});
Reset:
// clear arrays once clear btn is pressed
$(".ui-input-text .ui-input-clear").on("click", function () {
resetVal();
});
Result:
I think that you can use the same approach that I suggested to Ranjan.
Using a textfield like a buffer. First you need to detect when the keyboard appears and check if the first responder is the webview. Then you become a textview as the first responder.
When you are setting the text inside the input of the webview, you can add some logic to validate the number.
Here is a link of my example project with the solution, in your case you don't need change the inputView. But the approach is the same, use a Man in the middle.
Cant comment on https://stackoverflow.com/a/19998430/6437391 so posting as a separate answer...
This is the same idea as https://stackoverflow.com/a/19998430/6437391 but instead of switching the type, its the pattern that's switched.
This has the effect of not clearing the value on the textfield on focus when value does not match numeric format, for example, if the value has separators( 1,234.56 ).
$('input[type="text"]').on('touchstart', function() {
$(this).attr('pattern', '[0-9]*');
});
$('input[type="text"]').on('focus', function() {
$(this).attr('pattern', actualpattern);
});
I wrote this very simple function for my current project called insidelabel() that let's me add a description (label) for an input field inside of the input.
//Label inside of inputfields
function insidelabel(selector, name) {
$(selector).val(name);
$(selector).css({'color':'#999'});
$(selector).focus(function () {
//Input Value
if ($(this).val() == name) { $(this).val(''); }
$(this).css({'color':'#000'})
});
$(selector).blur(function () {
if ($(this).val() == '') { $(this).val(name); }
if ($(this).val() == name) {
$(this).css({'color':'#999'});
}
});
}
insidelabel('.t', 'name');
insidelabel('.p', 'enter password');
So when an input is focused the text disappears and when it blurs it has the same text again.
<form method="get" action="">
<input type="text" class="t" value="" /><br/>
<input type="password" class="p" value="" />
</form>
However now I wonder how I could extend that function to have a label inside of password fields as well! Sounds weird... Explanation: I want a password field (with type="password") to have a readable label (like "enter password") inside of it. Once the user enters text the password should be unreadable (dotted). Really bad explanation, I know, but I think you might get what I mean.
I wonder what's the best way to do that? Should I query if an input field is type="password" and if so I set it to type="text" - once text is entered I set it back to type="password" again. Any idea what's the best solution for that?
Here is my example: http://jsfiddle.net/R8Zxu/
If you use a real <label> positioned under the (transparent) <input> instead of faking it with the value attribute (which has some major accessibility implications) then you can do something like: http://dorward.me.uk/tmp/label-work/example.html
Don't try to change the type of an existing input. Internet Explorer won't let you.
OK for web applications, but if you want to use page on iPhone application then it does not works properly, for correct answer see refer this - http://blog.stannard.net.au/2011/01/07/creating-a-form-with-labels-inside-text-fields-using-jquery/
Yes, that would be the right approach. This is known as a 'watermark' on a text field, and since password input fields use a different text display mechanism, when the watermark is active, you would want to switch it to a text type. OnFocus, you would switch it out (and if needed) focus on the new text field.
Just remember, you'll want to do the conversion to a type="text" before messing with the value; there are restrictions when it is a type="password".
Can someone show me some example for restricting user input (on input tag) in Javascript?
Something that when we set the input (type="text") to only accept numeric, so it will ignore any other input except for numeric...
I think it's handy for number input (such as zip, credit card, money, value, score, date etc...), and if you can please show me how to create input with pattern, something like:
Please Input Date:
|-----------------|
| / / |
|-----------------|
PS:
I heard WebForms 2.0 will support this in the future... (Acid 3 compliant browser?)
input type="date"
input type="time"
input type="number"
input type="money"
But it was only news from future :D
This might help you.
http://www.w3schools.com/jsref/event_onkeydown.asp
<html>
<body>
<script type="text/javascript">
function noNumbers(e)
{
var keynum;
var keychar;
var numcheck;
if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
numcheck = /\d/;
return !numcheck.test(keychar);
}
</script>
<form>
<input type="text" onkeydown="return noNumbers(event)" />
</form>
</body>
</html>
This question has already an accepted answer, but I think there is a better solution to this. You don't have to implement that yourself on keydown etc., there are libraries for that. They call the technique you describe "input masks". Check out this jQuery plugin it does exactly what you want.
You can use specific libs like jQuery Validate (or whatever your JS framework offers) on form submit. The other solution is to control the value on the keyUp & blur events but it can become quite messy to decide what to do with ill-formated entry (especially when the format is a bit complex -- ie not just undesired characters). So, all in all, I'd recommend client-side control on submit.