I want to validate 7 first alphabet of my input box my code is doesn't work.
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(!this.value.match(/^http\:\/\//) && (txt_url.lenght >= 7 )this.value='http://'+this.value" />
There is a spelling mistake in the function which you have used.(txt_url.lenght).
It should be txt_url.length i believe. Also, if you want to validate a url, there are better regular expressions available on the net.
There are three reasons why that code doesn't work:
lenght should be length.
txt_url.length should be this.value.length.
You're missing a closing ) at the end of the if condition.
Working version:
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(!this.value.match(/^http\:\/\//) && (this.value.length >= 7))this.value='http://'+this.value" />
Demo: http://jsfiddle.net/J5Uxt/
Your code corrected is
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(this.value.match(/^http\:\/\//)==null
&& this.value.length>7)this.value='http://'+this.value;" />
But if you want to automatically put http:// prefix even for shorter domain names like ab.com
then you might use
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(this.value.match(/^h(t(t(p(\:(\/(\/)?)?)?)?)?)?/)==null)
this.value='http://'+this.value;" />
avoid inline (DOM zero) events and handle this sort of thing centrally
you have a typo in lenght.
are you quite sure you want to do this on key up, rather than, say, on blur, or form submit? It would surely be annoying for the user if you modified the field value every time he or she pressed a key
The below assumes blur, but you can change the event to whatever you want:
jQuery:
$(function() {
$('#text_url').on('blur', function() {
if (!/https?:\/\//.test($(this).val()))
$(this).val('http://'+$(this).val());
});
});
Native JS:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#text_url').addEventListener('blur', function() {
if (!/https?:\/\//.test(this.value))
this.value = 'http://'+this.value;
}, false);
}, false);
Related
I want to restrict an input text through a regular expression. In the first example I use the attribute onkeyup = "lettersOnly(this)" inside the HTML, as follows:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username" onkeyup="lettersOnly(this)">
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
</script>
It works but I learnt that this is a bad practice. I found other solution avoiding that, and setting someVariable.onkeyup inside <script> tags. However, my goal is to find another way to get the same result using addEventListener ('keyup', lettersOnly, false). I researched a lot for this specific situation but no answers. Is it possible? I tried the following:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
<!--No more “onkeyup” attribute.-->
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value.addEventListener('keyup', lettersOnly(input){
input.value = input.value.replace(regex, "");
}, false)
}
</script>
Doesn‘t work. My intention is to avoid the event handler in the html and use instead, the addEventListener. What is wrong in this last coding? Why doesn‘t work? I‘ll really appreciate your patience.
In the code that you said you have tried; the function lettersOnly() will never be called and addEventListener() will never be called.
You can simply change it as follow -
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
document.getElementById("username").addEventListener("keyup", lettersOnly(this), false);
</script>
Finally, I found myself a solution and I want to share it.
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
<!--No more “onkeyup” attribute.-->
</form>
<script>
let user = document.getElementById("username");
var regex = /[^a-z]/gi;
user.addEventListener("keyup", ()=>{
user.value = user.value.replace(regex, "");
})
// The “user” variable has been just to simplify a lot of repeated coding, as it is equivalent to “document.getElementById(“username”).
</script>
I don‘t know if this is the best and optimal way to solve my inquire but it works. No “ONkeyup” at all, but using, instead, addEventListener ("keyup", anonymous arrow function). I‘ll really appreciate if anybody has any other suggestion.
The main problem with your second piece of code was that you weren't actually attaching the eventListener to the input element since the outer lettersOnly function was also not called at any time. It appears you resolved this in your own answer, but I'm going to expand upon my comment and suggest using keydown instead.
In the following snippet, I changed the eventListener to attach to keydown instead of keyup. Then we test if the new key (via event.key) matches our regex with .match. If the key pressed is a non-letter character, the match will be non-null, so we want to utilize event.preventDefault() to interrupt the new key from being added to the input value.
Note: this has the added benefit of not needing to use replace or replaceAll to remove the invalid character.
var regex = /[^a-z]/gi;
function lettersOnly(event) {
if (event.key.match(regex) !== null) {
// Since it is an invalid character, we will prevent default
event.preventDefault();
// Log the key to the console for demonstration
console.log(event.key);
// Not needed since we preventDefault()
//event.target.value = event.target.value.replace(regex, "");
}
}
// `username` is equivalent to `document.getElementById("username")
username.addEventListener("keydown", lettersOnly, false);
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
</form>
I've been doing a lot of research on this and still can't find a good solution. Basically, I have this field in my form that should ONLY allow numbers. However, I'm able to enter mac special characters inside that field by doing:
Hold down option + shift and then pressing any button from keyboard (example: h j k l u i , etc).
Please see attached picture.
Can anyone help me on NOT allowing such characters inside the ID field? Thanks a lot in advance!
Here's my code:
LIVE DEMO
ID: <input formControlName="userid" type="text" pKeyFilter="num" placeholder="Numbers" pInputText>
There are many approaches to this problem. All of the provided solutions should work. My recommendation is Approach 2.
Approach 1
You can try to remove non number characters on the input event like this
<input
formControlName="userid"
type="text"
placeholder="Numbers"
oninput="javascript: this.value = this.value.replace(new RegExp('[^0-9]', 'gm'), '')"
pInputText
/>
Modified Demo
I tested this in Firefox and Chrome on MacOS and it seems to work fine.
Approach 2
To do this from your angular module:
Use a simple text input
<input
formControlName="userid"
type="text"
placeholder="Number"
pInputText
/>
Listen to changes and patch the value accordingly. Don't forget to register your observers on init.
registerChangeObservers() {
this.registrationFormGroup.get("userid").valueChanges.subscribe(val => {
this.registrationFormGroup.patchValue({
'userid': val.replace(new RegExp('[^0-9]', 'gm'), '')
}, { emitEvent: false });
});
}
ngOnInit() {
this.registerChangeObservers();
}
Especially note the { emitEvent: false } part. You need to set this to avoid recursion. This approach can fail if your model becomes invalid and therefore it's value changes to nil. For example this can happen if you set your input type to number, but a user manages to input a non number character. To avoid this make sure the input validation doesn't fail on special characters, e.g. by setting the input type to text.
Demo here
Approach 3
To avoid the display of modifying characters you can also listen to input events (i.e. key presses) instead of actual value changes. This is equivalent to approach 1.
To do so use this input
<input
formControlName="userid"
type="text"
placeholder="Number"
pInputText
(input)="onPress($event)"
/>
and add this function to your controller
onPress($event) {
this.registrationFormGroup.patchValue({
'userid': $event.target.value.replace(new RegExp('[^0-9]', 'gm'), '')
}, { emitEvent: false });
}
Demo 3
Note: I would generally avoid this approach because in my experience the suppression of modifying characters can have unintended side effects with some uncommon input methods, especially on mobile. The approach above (Approach 2) also works and is safer in my opinion. Although modifying characters are displayed, they will disappear on the next user action and will never be present in your model data.
You have already tried with:
<input type="number" pattern="[0-9]{10}" />
the following validates a 10-digit number, and I also think you should do a validation with JavaScript:
<input type="text" id="text" onblur="validaNumericos();" />
Function Javascript:
function validaNumericos(){
var inputtxt = document.getElementById('text');
var valor = inputtxt.value;
for(i=0;i<valor.length;i++){
var code=valor.charCodeAt(i);
if(code<=48 || code>=57){
inputtxt.value="";
return;
}
}
}
<input type="text" id="text" onblur="validaNumericos();" />
Use input type=number.
ID: <input formControlName="userid" type="number" pKeyFilter="num" placeholder="Numbers" pInputText>
If you don't like the dial controls on the right side, you can disable them with this in your css:
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type=number] {
-moz-appearance:textfield;
}
Here is a fork of your demo with all the changes.
Well, if you are looking for a regex answer (based on your tag), you can test on the length of the pre-regex value vs. the length of the post regex value.
if there are extra characters, the lengths will not match.
[0-9]+
I want to restrict the input in multiple forms and I'm trying to remove letters from the input on the keyup event. The problem is that It seems to work only on type="text" inputs, but I need it on type="number" inputs.
Fiddle.
NOTE: I need this working at Firefox and IE. On chrome this
functionality isn't neccesary.
$(function(){
$('input[type="number"], [type="text"]').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number">
<input type="text">
You shouldn't have a space between the element selector and the attribute selector.
input [type="number"]
Should be:
input[type="number"]
The [type="text"] happens to work because it matches all elements with a type attribute that is set as text. It really should also be:
input[type="text"]
And the whole selector:
'input[type="number"],input[type="text"]'
There are also issues with the function - the two split('').reverse().join('')? Not needed.
A better approach for this function would be:
$('input[type="number"], input[type="text"]').keyup(function(e) {
this.value = this.value.replace(/[^0-9-]/i, '');
})
Remove Space in between element(input) and attribute([type="text"])
$(document).ready(function(){
$("input[type='text'],input[type='number']").keydown(function(){
$("input[type='text']").css("background-color", "yellow");
});
$("input[type='text'],input[type='number']").keyup(function(){
$("input[type='number']").css("background-color", "pink");
});
});
</script>
The bug was happening because the way IE11 populates the value attribute is strange for type="number".
When I type '1a' then then this.value is '1a', so your code executes correctly.
When I type 'a1' then then this.value is '', so isNaN('') becomes false and your code doesn't execute.
I don't why IE11 is so strange.
I would recommend not using the isNaN and generally improving your coding standards. There were many minor issues already noted in comments.
Here is an example which works in IE11. (This still has some issues testing in Chrome, but you already stated you are not interest in Chrome)
$(function(){
$('[type="number"], [type="text"]').keyup(function() {
this.value = this.value.replace(/\D/g, '');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number">
<input type="text">
You can try this following link,
https://jsfiddle.net/tkfnxpvy/4/
use
$('input[type="number"],input[type="text"]'.keyup(function(e){
});
Okay guys, thanks for all the help, I think I finally solved here.
JSFiddle
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" oninput="this.value = this.value.replace(/[^0-9.,]/g, '');">
<input type="text" oninput="this.value = this.value.replace(/[^0-9.,]/g, '')">
I am trying to restrict user's input if user is trying to type some characters (like space). To do so I found this post.
But I wanted to make it through HTML's onkeypress attribute. And faced with problem, that if I specify function to return false, then nothing will happen, but if I return false right in HTML's attribute - input won't happen.
I can't understand what am I doing wrong. Can you please tell me how to solve this?
function doMatch() {
return false;
}
$('#test').keypress(function() {
//return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeypress="doMatch();" id="test"/>
But I wanted to make it through HTML's onkeypress attribute.
I recommend you to not do that, since it's better to keep the Javascript behavior out of your HTML code. The name os this technique is Unobstrusive Javascript.
But if you really want to do that, you must use the return keyword to make it work:
<input type="text" onkeypress="return doMatch();" id="test"/>
You just need to add return before doMatch();
function doMatch() {
return false;
}
$('#test').keypress(function() {
//return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeypress="return doMatch();" id="test"/>
On my page im working on, are a lot of input-forms.
I want to check the user inputs before submit.
Example
HTML/PHP
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
and actually im doing the following in Javascript
Javascript
function dataValidation() {
error=false;
var adress = document.getElementById('adress').value;
var amount = document.getElementById('adress').value;
if (adress == ""){
error=true;
}
if (amount >0 && amount < 999){
}
else {
error=true;
}
if (error == false){
document.forms["myForm"].submit();
}
}
So, basically this works fine for my, but the problem is, i have to create that function for every form, and add a IF for every field
So, im looking for a better solution
Idea 1 : Add a list, wich provides the types of input, like
adress = not empty,
amount = >0 && <999,
and then create a function, which checks all fields with that list
Idea 2: Add a tag or something directly to the input field, what it should contain. and then create a function which checks all the fields
Does somebody have a Idea how this can be done, and would like to help/advise me?
you could try this by jquery as:
your html:
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
<input type="button" id="check_input">
and apply jquery for all input field
$("#check_input").click(function() {
$("input").each(function() {
var element = $(this);
if(element.val() == "") {
element.css("border","1px solid red");
element.attr("placeholder","Field is empty");
return false;
}
});
});
if you have multiple forms with same fields try to call validation externally it will reduce some of your work apart from that i dont know any other method so lets wait for others reply
You might wanna consider using HTML5.
HTML5 can save time writing JS validations. For example to validate an email address you could use the following:
<input type="email" name="email" required />
Notice the type="email" and required. Instead of using js for validating, you could use HTML5 form attributes with Regular Expression Patterns.
For example If I want to create an input field which accepts only one numbers and 3 uppercase letters, I can easily do with it using a RegEx pattern:
<input type="text" pattern="[0-9][A-Z]{3}">
Read a little bit more on HTML5 and RegEx. It could help you.