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]+
Related
I have simple text input:
<div style="float:right" class="xField">
<input id="userLength" name="userLength"/>
<label style="margin-left: 3px;">m</label>
</div>
I need this input to only accept numbers and if the number is a whole number, it should only allow 5 characters i.e. 12345. If the number includes a fraction, it should then allow for 8 characters i.e. 12345,99.
I've tried adding maxlength to the input but that only works with one of these conditions at a time.
How can I accomplish this?
You could use the pattern attribute and provide a regular expression that supports your requirements.
for example (this does not forbid entering invalid data, but will mark the field as invalid while the pattern is not matched).
<div style="float:right" class="xField">
<input id="userLength" name="userLength" pattern="\d{1,5}(,\d{1,2})?" />
<label style="margin-left: 3px;">m</label>
</div>
All you need is this:
<form action="/" id="form">
<input pattern="\d{0,5}([,.]\d{1,2})?" title="max 5 digits and 2 decimals">
<button type="submit">submit</button>
</form>
This will allow the user to enter as many characters as he wishes, but upon form validation the form will fail if the pattern is not satisfied.
The pattern is a regex and reads as follows: from 0 to 5 numeric characters and optionally up to two decimals
Also, if the input should not be empty you can add a required attribute like this
<input ... pattern="" required>
This causes also a validation failure if the input is empty.
When the pattern is not met, the browser will show whatever is inside title="" to the user.
Play around with this fiddle so you can see how the validation errors are presented: https://jsfiddle.net/aqohfsrj/2/
Also, if you want to do something with the input value using javascript, I recommend binding to the form's submit event and not the button's click or input's enter-keydown events
document.getElementById("form").addEventListener("submit", e => {
// if this code is executed it means the validation passed, otherwise errors
// are displayed to the user and this code is not run.
e.preventDefault(); // <-- to avoid trying to use the form's action i.e. the browser will not navigate.
});
To understand the regex I used you can see this regex101 file:
https://regex101.com/r/aHLI6u/1
Finally a recommendation:
Try to avoid maxlength for validation; often times I have had to fill in a form online that asks for a credit card for example, and it is limited to maxlength="16" which at first sounds like a good idea, but what if you try to copy your credit card from a note you have or something, and it was stored as 5430-0000-1111-2222 (with dashes). It feels rude to disallow pasting more chars than allowed, when all the user wanted was to paste, then edit, then submit. I would let the user add as much content as they want, so they can edit in-place to remove parentheses (for phones), remove currency signs (for money), remove dashes (for credit cards) and validate after they have submitted the form.
When I declare JS.
var test = $("#test").val();
Then the "number validaion" is not working on the browser side.
<input type="number" id="test" name="test" required>
Is there any chance to declare $("#test") and use HTML5 in input validation as well (such as required, number validation etc.)? Or I have to to do it on JS side.
It have to be declared to use it later in my AJAX post scipt.
Thanks :)
Use parseInt("stringOfNumber") to get integer from string. When inputting data, you write strings, not numbers.
This is how you use the input type number in HTML5:
<input type="number" name="cost">
Here is a working example of the http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_number.
If you want to add validation try this:
<input type="number" pattern="[0-9]*" name="cost">
Here is a working example of the pattern attribute http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_pattern
Note: Both the input type number and the pattern attribute have limited browser support.
You can check if it's Not a Number, and then invert it.
if(!isNaN(test))
{
// Is a number
}
If you use jQuery, you could use
if($.isNumeric(test))
{
// Is a number
}
Don't rely on Client Side validation though, as it can be easily avoided and some browsers don't support it. E.g: JavaScript validation can be avoided by disabling JavaScript.
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.
We currently use the following logic to mask the inputs:
Set a specific class to several inputs <input type="text" class="typenumdec" />
In document.ready() bind a propertychange event with the rules:
$('table tbody > tr > td.tiponumdec').children('input[type=text], input[type=number]')
.add('input[type=text].tiponumdec, input[type=number].tiponumdec').bind('input propertychange', function () {
$(this).val($(this).val().replace(/[^0-9,]/g, ''));
});
But we wanted to centralize the logic and make it more streamlined for our developers so they dont have to add/modify the bindings.
Something like this:
Developer defines somewhere the format and its name (javascript globals? key/value array?):
var formatmoney1 ='5.2'; //5 integers and 2 decimals
var formatmoney2 ='5.3'; //5 integers and 3 decimals
var formatdays ='3'; //3 integers
Developer sets the format to a data-atribute or css class (recommended option?)
<input type="text" class="formatmoney1" data-formatx="formatmoney1" />
On document.ready() a generic function parses the format definitions and the inputs in order to mask them depending on its assigned format
PS: we saw this plugin that seems interesting in order to cover part of the mask logic (your opinions?): http://igorescobar.github.io/jQuery-Mask-Plugin/
We are currently using HTML 5 to make 99% of all validations. You can use them in a very understandable and developer-friendly way.
For example this code will prevent entering everything else then an email address:
<input type="email" />
Or use this with custom regex:
<input type="text" name="dutch_zip_code" pattern="[A-Za-z]{4}[0-9]{2}" />
You can also set the pattern in javascript / jquery like this:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="jquery.mask.js"></script>
</head>
<body>
<input type="text" name="dutch_zip_code" data-validation-type="dutch_zip_code" />
<script>
$(document).ready(function()
{
$('input[type=text]').each( function()
{
var type = $(this).data('validation-type');
if (type == 'dutch_zip_code')
{
$(this).attr('pattern', '[A-Za-z]{4}[0-9]{2}');
//
// Use jquery mask plugin:
// https://plugins.jquery.com/mask/
//
$(this).mask('0000SS');
}
}
);
});
</script>
</body>
</html>
You can use modernizr for backwards compatibility.
As mentioned in comments, if you use bootstrap (http://getbootstrap.com/), there is the excellent Jazny Bootstrap (http://jasny.github.io/bootstrap/) plugin which makes input masks extremely easy and tidy.
Here is a fiddle which demonstrates your 3 formats: http://jsfiddle.net/JNfxa/9/
Here is the HTML:
<label>formatmoney1</label>
<input type="text" class="form-control" data-mask="99999.99" data-placeholder=" ">
<label>formatmoney2</label>
<input type="text" class="form-control" data-mask="99999.999" data-placeholder="0">
<label>formatdays</label>
<input type="text" class="form-control" data-mask="999" data-placeholder="#">
And that is it, no extra CSS or JS required.
I have used three different examples for the data-placeholder attribute, this is the character that appears for the empty digits that the user must complete, default is '_'. Where I have used '9', this will restrict the user to enter a number, there are other options detailed here: http://jasny.github.io/bootstrap/javascript/#inputmask
Now, to centralise the data-mask to a single, maintainable variable, you could bind it to an observable ViewModel property using KnockoutJS. (http://knockoutjs.com/index.html)
You can do a lot more than this, but here is an updated fiddle: http://jsfiddle.net/JNfxa/11/
Now there is some JS, to declare our observable properties containing each of the masks:
vm = {};
vm.formatmoney1Mask = ko.observable("99999.99");
vm.formatmoney2Mask = ko.observable("99999.999");
vm.formatdaysMask = ko.observable("999");
ko.applyBindings(vm);
Knockout has an attr binding, which lets you bind the value of an observable property to a custom HTML attribute of your choice. More details here: http://knockoutjs.com/documentation/attr-binding.html
The HTML changes slightly to bind the data-mask attribute instead of setting it directly:
<label>formatmoney1</label>
<input type="text" class="form-control" data-bind="attr: { 'data-mask': vm.formatmoney1Mask }" data-placeholder=" ">
<label>formatmoney2</label>
<input type="text" class="form-control" data-bind="attr: { 'data-mask': vm.formatmoney2Mask }" data-placeholder="0">
<label>formatdays</label>
<input type="text" class="form-control" data-bind="attr: { 'data-mask': vm.formatdaysMask }" data-placeholder=" ">
What's great about this, is you can update the mask observable on the fly, and the HTML will automatically update without refreshing the page, so you could have e.g. a radio button control to choose different input mask types.
I would HIGHLY recommend taking a look at this plugin- Robin Herbots inputMask
This plugin is robust, has alot of callbacks/options and is actively developed. One of the major advantages of this plugin are the extensions which is where you define masks and aliases.
You can define a mask however you want..if you wanted to extend the out of box decimal mask definition you could do it like this...
$.extend($.inputmask.defaults.aliases,
{
'formatmoney1':
{
mask: "99999.99",
placeholder: "_____.__",
alias: "decimal"
},
'formatmoney2':
{
mask: "99999.999",
placeholder: "_____.___",
alias: "decimal"
}
}
Once you have defined your mask, and extended the out of box decimal definition then you could pick up all elements and apply the inputmask.
$(document).ready(function()
{
$('.formatmoney1').inputmask('formatmoney1');
$('.formatmoney2').inputmask('formatmoney2');
});
This mask allows you to have a very high amount of control through the numerous callbacks and is highly configurable by setting default options.
Another option you have with using this plugin is to take advantage of the data-inputmask attribute. For example,
<input type="text" data-inputmask="'alias':'formatmoney1'" />
Be sure you look through the Usage page as well as the extension files, there are a few of them but it looks like you will want to use the jquery.inputmask.numeric.extensions.js
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);