How to properly control data input? - javascript

There is a task to supervise input in . It is necessary to give the ability to enter only strings of numbers ([0-9]) into the entity input. At the same time, if something else is entered, then do not overwrite value and do not display incorrect input in the input. I can't find a solution for my case. Validity check ( target.validity.valid ) didn't work either because I have control over the minimum and maximum lengths. At the same time, I have a universal function for several inputs, but only the entity needs to be checked. Please tell me how to correctly implement the check for input [0-9] and so that nothing else can be entered.
The examples that are on the resource are not suitable because they do not take into account the control of the minimum-maximum length
Below is a shortened code example
const [inputState, setInputState] = useState({title : "", entity: ""})
const handleChangeInputValue = (event) => {
const { target } = event;
const { name, value } = target;
// Need to check for numbers
setInputState({ ...inputState, [name]: value });
};
<input
required
minLength={5}
type="text"
placeholder="Enter name"
name="title"
value={inputState.title}
onChange={handleChangeInputValue}
/>
<input
required
minLength={13}
maxLength={15}
type="text"
placeholder="Enter entity"
name="entity"
value={inputState.entity}
onChange={handleChangeInputValue}
/>

you can use HTML 5
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>

if(name==='entity' && !value.match(/^\d+$/)) {
return
}

Related

get input value in typescript

I had 2 input value, I need to do validation on first input value which is credit card number input, get input value on ts file and check validation on API while user still typing on second input, example of my first input value: 4444 4444 4444 4444, so i need to use subString() to get first 6 number before do validation,
this is what I had tried;
html file
<div>
<input
(keypress)="numberOnly($event)"
class="input"
type="text"
(keyup)="onKey($event)"
[(ngModel)]="creditCardNo"
/>
</div>
<div>
<input
class="input"
type="text"
[(ngModel)]="cardHolderName"
/>
</div>
ts file
onKey(event) {
this.creditCardNo = event.target.value;
const test = this.creditCardNo
.replace(/\s/g, '')
.toString()
.substr(0, 6);
this.paymentService.getCreditCardDetail('JPJSMN', test).subscribe(res => {
if (!res) {
return;
}
console.log(res);
});
}
using (keyup)="onKey($event)" to get value change, and do a validation on ts file based on response I get, however I notice if Im using (keyup)="onKey($event)", it doesnt detect copy and paste, and it keep requesting API,if there are better practice to solve this ?
You can opt to create a custom 'digitOnly' Angular directive.
A great guide on how to do this can be found here:
https://codeburst.io/digit-only-directive-in-angular-3db8a94d80c3
The directive shown in the tutorial address issues such as copy and paste.
If you just want to get the model updated when the user pasts something the same way as editing the value, you can just use
(ngModelChange)="pasteEvent($event)"
<div>
<input
(keypress)="numberOnly($event)"
class="input"
type="text"
(ngModelChange)="pasteEventcreditCardNo(creditCardNo)"
[(ngModel)]="creditCardNo"
/>
</div>
<div>
<input
class="input"
type="text"
(ngModelChange)="pasteEventcardHolderName(cardHolderName)"
[(ngModel)]="cardHolderName"
/>
</div>

Automated Form Filling

Iā€™m looking for a way to automate a form.
Here are the details:
Extract a certain number (displayed in its html)
Do some calculations on the extracted number (percentage of that number)
Then automatically fill the remaining input fields with the result instead of typing it out.
This is a common occurrence in forms. The solution depends on what framework / libraries you're using. Assuming you're using none, here is how you might go about it:
https://jsfiddle.net/f52h1smj/1/
rough HTML:
<form>
<label for="number">Number: </label>
<input id="number" type="number" />
<br /> <br />
<label for="calculatedNumber">Calculated Number (50%): </label>
<input id="calculatedNumber" type="number" disabled="true" />
</form>
JS:
(() => {
//get the form element nodes
const $number = document.getElementById("number");
const $calculatedNumber = document.getElementById("calculatedNumber");
//add an event listen to the value you're going to use to pre calculate the other fields
$number.addEventListener("keyup", (e) => {
//it's value is available like so
const value = e.target.value;
//do some validation so that you're calculations don't throw exceptions
if (Number(value) !== 0 && !Number.isNaN(value)) {
//set the value of the other inputs to whatever you like by setting the 'value' property of the node.
$calculatedNumber.value = value / 2;
} else {
$calculatedNumber.value = null;
}
});
})();
These things become a lot simpler in frameworks like React and Angular.

display a hidden input field when enter value on a particuloar input filed

anyone could help me out on how i could achieve this with either javascript or jquery maybe to get the following as mentioned below
say i have this field1
<input type="text" name="field1" value="">
and then i have this field2
<input type="hidden" name="field2" value="">
what i mean to say the field2 should be hidden but if someone enters some value in field1 then field2 shows but if no value on field1 then it disappears?
thanks in advance and appreciate your time and help
You'd get the first field, check if it has a value, and toggle the second field based on that, but you should not be using a hidden input, but instead hide it with CSS
$('[name="field1"]').on('input', function() {
var el = $('[name="field2"]').toggle( this.value !== "" );
if (this.value === "") el.val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="field1" value="" placeholder="type something">
<br><br>
<input type="text" name="field2" value="" style="display:none">
As you've also tagged your question with JavaScript it seems worth offering the following:
// retrieving the first - if any - element with its
// 'name' attribute equal to the value of 'field1':
var input = document.querySelector('[name=field1]');
// adding an event-listener to that element, listening
// for the 'input' event (keyup, paste, copy...) and
// assigning the method's anonymous function as the
// event-handler:
input.addEventListener('input', function(e) {
// 'e': here unused, is a reference to the event
// which triggered the function to be called; using
// e.type will give the specific event, if required
// (and other properties are, of course, available).
// retrieving the first - if any - element with has
// its 'name' attribute equal to 'field2':
var conditionalInput = document.querySelector('[name=field2]');
// if the value of the <input> element that received
// the event has a value that, when leading and trailing
// white-space is removed, results in a truthy
// evaluation (the string length is non-zero):
if (this.value.trim().length) {
// we set the display style of the conditionally-
// shown <input> to 'block', you could instead use
// 'inline-block' if you prefer:
conditionalInput.style.display = 'block';
// otherwise, if the length of the trimmed-value is
// zero (falsey):
} else {
// we set the display style of the conditionally-
// shown <input> to 'none':
conditionalInput.style.display = 'none';
// and also remove its entered value:
conditionalInput.value = '';
}
});
var input = document.querySelector('[name=field1]');
input.addEventListener('input', function(e) {
var conditionalInput = document.querySelector('[name=field2]');
if (this.value.trim().length) {
conditionalInput.style.display = 'block';
} else {
conditionalInput.style.display = 'none';
conditionalInput.value = '';
}
});
<input type="text" name="field1" value="" />
<input type="text" name="field2" value="" />
In your HTML please note that I've adjusted the <input> element's type, from 'hidden' to 'text', this is because some browsers ā€“ I believe mostly Internet Explorer ā€“ has, or had, issues when changing the type of an <input> element dynamically.
If your use-case doesn't depend on cross-browser compatibility then you can, of course, change the type (conditionalInput.type = 'text'/conditionalInput.type = 'hidden') rather than the display.

Referencing the length of a HTML number form element?

I have a form that takes numbers, and there is a specific (Phone number, or phNo) form element that I want to only accept 7 digits in length (no more, no less). Using Javascript the Idea is:
If element length not equal to 7: true else false
Here is my code:
var phNo = document.getElementsByName('phNo'); //here I try to get
the form value in the form of an object. This is where I think I am going wrong
var phNoString = phNo.toString(); //Not to sure if I need this line or not, read somewhere that .length only works on a string
if(phNoString.length != 7) {
//Do something for false
return;
} else {
//Do something for true
}
<form id="myForm" action="form_action.asp">
First name: <input type="text" name="fName"><br>
Last name: <input type="text" name="lName"><br>
Phone Number: <input type="number" name="phNo" max="7"><br>
Credit Card Number: <input type="number" name="cardNo"><br>
</form>
<input id="submit" type="button"value="Submit"onClick="detailsSubmit()">
var phNoString = phNo.toString();
This line will return [object HTMLInputElement], you need to use phNo.value if you want the value the user typed inside the input.
Not really related to the problem, but <input type="number" name="phNo" max="7"> here the max attribute only means the highest number possible in that input is 7. Using a browser that supports html5 inputs it's giving me an invalid highlight if I try to enter any phone number.
I would change it to a simple text field and use the maxlength attribute, which is probably what you intended;
<input type="text" name="phNo" maxlength="7">
"getElementsByName" returns a collection type, you should be doing like this to read the value from the element.
var phNoString = document.getElementsByName('phNo')[0].value;
if(phNoString.toString().length != 7) {
//Do something for false
return;
} else {
//Do something for true
}
If you did decide to leave it as a number input, you don't need to convert it to a string. Phone Numbers can't start with 0, so the smallest number would be 1000000. If your input has a max of 7, then you can check that the value is greater than that.
var phNoString = document.getElementsByName('phNo')[0].value;
if(var phNoString > 1000000){
// truthy
}else{
// falsey
}
The document.getElementsByName() function is depreciated in HTML5. See note in w3school site. Use document.getElementById() instead and add an ID tag to your phone input control.
Also use input type="tel" for your phone numbers. That way the browsers, especially on mobile devices, know how to correctly display the inputted value on the screen.
Finally, note the use of regular expressions to do a validation check on the inputted phone number. Also, it is important to note, the HTML5 regex validation runs after the JavaScript function executes. Below is a code snippet that you can sink your new developer teeth into:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
Phone Number (format: xxx-xxx-xxxx):: <input type="tel" id="phNo" name="phNo" pattern="^\d{3}-\d{3}-\d{4}$"/><br>
<button type="submit" name="submit" onclick="checkphonelength()">submit</button>
</form>
<script type="text/javascript">
function checkphonelength(){
var phNoStringLength = document.getElementById('phNo').value.length;
if(phNoStringLength === 12) {
alert("true");
return true;
}
alert(false);
return false;
}
</script>
</body>
</html>

Number with decimal input in React?

I have a number input within a React component, and it needs to accept numbers with a decimal point. Usually, entries will be in the fractions of a cent, like 0.0073, that kind of thing.
<div className="form-group">
<label htmlFor="rate" className="col-sm-6 control-label">Rate:</label>
<div className="col-sm-2">
<input type="number"
title="Rate"
id="rate"
className="form-control"
value={this.props.rate}
min="0.00"
step="0.001"
max="1.00"
onChange={()=>{
console.log('page rate changed');
this.props.setrate($('#rate').val());
}} />
</div>
</div>
The issue is that with every keystroke, it's resetting the rate for the app, and then putting that value into the input. So it goes like this:
User types 0, the value is set to 0, and 0 is displayed.
User types ., 0. isn't a valid number, so the input is cleared.
Can anyone think of a workaround? I know I could just use a normal input, but type="number" leads to some nice stuff in various browsers.
<input
type="text"
value={this.props.rate}
onChange={this.onAmountChange}
/>
type should be text and input value should be defined by regex.
onAmountChange = e => {
const amount = e.target.value;
if (!amount || amount.match(/^\d{1,}(\.\d{0,4})?$/)) {
this.setState(() => ({ amount }));
}
};
regex here means: start with a number and add as many as you want. then optionally end with decimal numbers up to 4 decimals.
You can do something like this
const floatRegExp = new RegExp('^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$')
const handleValidationOnChange = (e, v, onChange) => {
const { value } = v
if (value === '' || floatRegExp.test(value)) {
onChange(e, v)
}
}
const InputFloat = props => {
if (typeof props.onChange !== 'function') {
return <Form.Input { ...props } />
}
const { onChange, ...parentProps } = props
return <Form.Input
{ ...parentProps }
onChange={(e, v) => handleValidationOnChange(e, v, onChange)}
/>
}
Form.Input can be any Component that has a value.
You will have to later check for '', that is unavoidable.
<input type="number"
title="Rate"
id="rate"
className="form-control"
value={this.props.rate}
min="0.00"
step="0.001"
max="1.00"
presicion={2} //very important
onChange={()=>{
console.log('page rate changed');
this.props.setrate($('#rate').val());
}} />
{(text) => this.setState({ value: text.replace( /^[-+]?[0-9]+\.[^0-9]+$/, ''), })}
This will replace any input on runtime if there is any input except decimal number
I had a similar issue where I had decimal numbers in a database and reading them into React. By default, the decimal would show up with trailing zeroes when displaying in React. Trying to display without the trailing zeroes gave me the issue that you describe above. My issue may be slightly different from what you are looking for, but I think it would help others. What I had to do:
Pull the data from the database with the desired formatting. For example: instead of select mynumber from mytable I did select (TRIM(mynumber)+0) as mynumber from mytable. This automatically removes the trailing zeroes.
I then read these values into the React JS script and set in state. These become the value of the input fields.
Then rather than preventing users from entering a non-number value I simply change the background color of the input field to red if the value is not a number.
if (isNaN(mynumber)) {
bgcolor = "#fdd" //Add this to your input style
}
I found the red background above good enough for my purposes but you can also implement an additional check when the user clicks the save button.
I've tried your code and wasn't really affected by your issue, the value is indeed empty when you type the last dot, but the input is not reset.
The thing I changed from your implementation is that I get the input value from the onChange event rather than use jQuery.
<input onChange={e => this.props.setrate(e.target.value)} />
But I doubt your issue comes from that though.
What you could do is not to call your setrate function when you detect an ending dot in your string. Your state will not be modified until the user types a valid number, so one keystroke after the 0..
<input onChange={e => {
const str = e.target.value
if (str.charAt(str.length - 1) === '.') { return }
this.props.setrate(str)
}} />

Categories