Deleting a negative value from number input and validation - html

I feel that this is a dumb question, sorry.
I have an input with the number type and I want to add some validation to it. It is not required, so an empty string should be valid, negative numbers too, but not the - sign.
Consider now I've entered -102 into that field and removing symbols one by one, watching for changes.
Here's the basic codepen for it. As you can see, when there's just a - sign left the value (event.target.value) is an smpty string, which should be valid.
So, how can I check if there is only a minus sign left and mark this field as invalid?
const el = document.getElementById('input');
el.addEventListener('keyup', (e) => {
const value = e.target.value;
console.log(value)
})
<input type="number" id="input">

you can use pattern to only accept positive or negative number
in JS you can call method checkValidity() or use {yourinput}.validity.valid to check if value entered in input is valid or not
in css you can use the pseudo class :invalid to design your input when value entered don't match the pattern/field expectation
const el = document.getElementById('input');
el.addEventListener('keyup', (e) => {
console.log(el.checkValidity());
if (!el.checkValidity()) {
//treat case input invalid
}
})
input:invalid {
color: red;
}
<input type="number" id="input" pattern="\d+">

Related

Is there a easy way to handle input type="number" as a default negative value?

I've tried filling the value on init with a "-" sign but only got the Error-Message:
The specified value "-" cannot be parsed, or is out of range.
Another attempt was to just accept every value as negative if it doesn't start with a "+" sign but when reading the value property the sign wasn't included.
Does anyone know an easy way to handle an input type="number" as a negative and only make it positive when explicitly stated?
Preferably in a user-friendly way. I don't want a check-box to handle that.
Specifics:
i have an input Field in html
<input type="number" #testAmount>
I want to handle the value as negative when not explicitly stated otherwise.
so my first attempt was this in TS:
#ViewChild('testAmount') testAmount: ElementRef<HTMLInputElement> | undefined = undefined;
ngOnInit() {
if(!!this.testAmount){
console.log('set amount value');
console.log(this.testAmount.nativeElement.value);
this.testAmount.nativeElement.value = '-'
}
}
that's when i got the error message above:
The specified value "-" cannot be parsed, or is out of range.
Attempt 2:
In my second attempt figured to just accept any value and treat it as negative and only once the user puts a "+" before the value it would be a positive.
but that didn't work out, because when i read the value like this:
console.log(this.testAmount.nativeElement.value)
i was given the value without the + sign, presumably because it was interpreted as a number and thus the + sign was automatically removed.
To Be clear
All i want is that the user doesn't have to add the minus sign every time he adds a value, because negative values will be the norm.
But a positive value shall still be possible it is just rather rare.
Solution?
Best solution i've found so far is to give my input a KeyDown event and handle the very first key-input, it's not perfect but i think it'll get the job done most of the time:
inputHasBeenMade = false
onKeyDown(event: KeyboardEvent) {
if(!this.inputHasBeenMade && !!this.amount){
if(event.key !== "+"){
event.preventDefault()
this.amount.nativeElement.value = '-' + event.key
}
this.inputHasBeenMade = true
}
}
i don't think it's a good solution so i won't write it down as an answer (for now) in the hopes that someone will come up with a better solution.
type number can't have a "-" string.
you can specify -78 or some other number without the ""
Change
let myValue = '-';
this.testAmount.nativeElement.value = myValue
To
let myValue = -5;
this.testAmount.nativeElement.value = myValue;
You are creating a minus symbol when you wrap it with a single ' or a " double quote, and this makes it a string. Remove the quotes and it will be an integer.
You can also look at casting a string to an int if that's required, but not good practice.

How to restrict user from entering numbers or special characters in to text input field in react class components

im trying to restric user from entering numbers using regex in to my text type input . how can i achieve it ,
nameChangeHandler=(e)=>{
const userInput={...this.state.userInput};
const reg=/[0-9]/;
if(reg.test(e.currentTarget.value))
e.preventDefault();
userInput[e.currentTarget.name]=e.currentTarget.value
this.setState({
userInput
})
}
<input id="nameInput" type="text" name="username" value={username} onChange={this.nameChangeHandler} />
This is what i have tried doing
The regex pattern to "not allow" for numbers (= check whether numbers are not in the string): /^([^0-9]*)$/
Example regex to additionally check for special characters ($ and %):
/^([^0-9$%]*)$/
Assuming your current handler works, this should prevent users from typing a number and % and $:
nameChangeHandler=(e)=>{
const reg=/^([^0-9$%]*)$/;
if (reg.test(e.currentTarget.value)) {
this.setState({ ...this.state.userInput, username: e.currentTarget.value })
}
}

How to insert hyphen "-" after 4 digits automatically in TextBox in html5?

I have made validation in input field in html5 to get this format 03xx-xxxxxxx.
pattern="03\d{2}-\d{7}"
Now I want to add this hyphen symbol automatically after fourth digit.How to do that?
I must advice you against this type of input edit since it's usually frustrating when you need to edit typos.
Also I have no idea of the issues related to accessibility.
The input pattern only checks the data on submit, so it's not what you are looking for.
That said, here's one possible solution in JS:
// select the input element
var i = document.querySelector('input.hyphen');
// number of charatcers before the hyphen
var n = 4;
// run this function everytime the user release a key
i.addEventListener('keyup', function (event) {
// if there are more then n digits
if (i.value.length > n) {
// save the carret position
var s = i.selectionStart;
// remove all dashes
var t = i.value.replace(/-/g, '');
// beginning string with n digits
var b = t.substr(0, n);
// end string with what's left (maxLength)
var e = t.substr(n);
// join then with a dash
i.value = [b, e].join('-');
// if the caret was before the dash put it back to the saved position
if (s <= n) i.setSelectionRange(s, s);
// if the caret was next to the dash put it after
if (s == n+1) i.setSelectionRange(s+1, s+1);
}
});
<input class="hyphen" placeholder="0000-0000000" maxlength="12">
I have made validation in input field in html5 to get this format 03xx-xxxxxxx.
One alternative approach (without javascript) is to use three <input /> fields.
Working Example:
#country,
#region {
width: 16px;
}
#local {
width: 56px;
}
<input type="text" id="country" value="03" readonly />
<input type="text" id="region" pattern="[0-9]{2}" placeholder="88" />
-
<input type="text" id="local" pattern="[0-9]{7}" placeholder="8888888"/>

angularjs input type="number" not displaying negative numbers with a decimal fraction

When trying to enter a negative number with a decimal fraction into an input field of type number bound to a value with angularjs, the value is converted to NaN when the decimal character is a comma (as is standard in my country). The code is pretty simple:
<form>
<input type="number" ng-model="positiveMoney" />
{{positiveMoney}}
</br>
<input type="number" ng-model="negativeMoney" />
{{negativeMoney}}
</form>
app.controller('MainCtrl', function($scope) {
$scope.positiveMoney = 99.89;
$scope.negativeMoney = -99.89;
});
I have set up a plunker
to demonstrate this behaviour. When first running the plunker, the values are displayed correctly (and with a comma as a separator), but when deleting the minus sign and reentering it, the value isn't a number any more. I am using angularjs v1.2 and google chrome as my browser. When on the other hand I replace the comma with a decimal point, the value is displayed correctly, but this isn't the standard locale in my country (Croatia).
Edit:
Solved this eventually (with the help of Maxim Shoustin's suggestion) in a pragmatic way like this plunker:
app.directive('money', ['$filter',
function($filter) {
var MONEY_REGEXP = /^\-?\d+((\.|\,)\d{1,2})?$/;
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (MONEY_REGEXP.test(viewValue)) {
ctrl.$setValidity('float', true);
if (typeof viewValue === "money")
return viewValue;
else
return parseFloat(viewValue.replace(',', '.'));
} else {
ctrl.$setValidity('money', false);
return undefined;
}
});
}
};
}
]);
The directive accepts both commas and dots as the decimal separator. Also only two digits are allowed after the decimal point.

How can I make the HTML5 number field display trailing zeroes?

I have a field:
<input type='number' />
I'd like to punch in 0.50 without it “correcting it” to 0.5, so it would display 0.50.
I attached an on('change') event to the input you want to have trailing 0's
$('.number-input').on('change', function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
It just takes the value, casts it to a float, renders it to a string to the number of decimal places, and puts it back in as the value.
I've had a little play around with this and looked at the spec. It says that it must be a valid floating point number. There's one sentence in the definition of a valid floating point number it gives which caught my attention:
The best representation of the number n as a floating point number is
the string obtained from applying the JavaScript operator ToString to
n.
This means that the format will always be consistent with assessing what the number is, then using JavaScript's toString on that number. So no trailing 0s then.
So, you're going to have to resort to JavaScript. This isn't straightforward because document.getElementById('numInput').value = '0.50'; still gets corrected to 0.5, so the validation isn't triggered at onchange where the default action can be prevented, it's triggered internally.
This is the best solution I could come up with... it's a bit of a hack, and will need a bit of tweaking for robustness, but hopefully it'll do what you want:
var numInput = document.getElementById('numInput');
numInput.addEventListener('keypress', function () {
this.setAttribute('type', 'text');
});
numInput.addEventListener('click', function () {
this.setAttribute('type', 'number');
});
So if the user wants to enter the number by typing, it switches the input type to text, but when they click it, it converts it back to a number.
If you always want the trailing 0s no matter what the user types, then you could do it something like this:
var numInput = document.getElementById('numInput');
numInput.addEventListener('blur', function () {
if (this.value === '') {
return;
}
this.setAttribute('type', 'text');
if (this.value.indexOf('.') === -1) {
this.value = this.value + '.00';
}
while (this.value.indexOf('.') > this.value.length - 3) {
this.value = this.value + '0';
}
});
numInput.addEventListener('focus', function () {
this.setAttribute('type', 'number');
});
Edit: I think the second solution is more inline with what the user might expect, but it means that if the user types 0.5 it will be coerced to 0.50, so it depends if that's what you want.