Adding two values and send them to the server in ReactJs - reactjs

I am trying to add two values in my form to get the sum. One value is a number and the other is a string number and here is how they are implemented :
<AvGroup className="col-md-6">
<Label >Total Amount</Label>
<AvInput disabled type="number" name="total_amount" onChange={setFormValue}
value={(sumOfItems + parseInt(form.delivery_amount)) || ''} />
</AvGroup>
sumOfItems is a number and I am using parseInt to add a string value to it and then, send the result to the server. The problem is that I always get that error as a response from the server :
Cast to Number failed for value "NaN" at path total_amount
Any help on how I can fix this problem?!

If you want it to just work, change
value={(sumOfItems + parseInt(form.delivery_amount)) || ''}
to
value={(sumOfItems + (form.delivery_amount ? parseInt(form.delivery_amount)) : 0)}.
This will result in 0 being added to sumOfItems if parseInt can't parse out a number.

Related

React : How can I append '%' sign after the number is entered?

I want to append the % sign after the number is entered. How can I achieve this in React? I've concatenated the '%' sign but it is appearing after every number. How can I append it so that after entering the number e.g. 51 , the percent sign will appear?
Here's the code:
<InputBase
className={`milestone-percent-rate`}
autoComplete={"off"}
placeholder={"20%"}
maxLength="100"
value={this.state.percent_rate + '%'}
onChange={(e)=>{this.handleChange(e, "percent_rate")}}
/>
you can write the append logic in the handleChange method like below .
this.setState({percent_rate,e.value+'%'})

How to implement input text masking in React-Native?

The mask is needed: 90.99%, where:
9 - optional digit
0 - required
%,. - relevant characters '%' and '.'
For example:
Input / Result
1 ---> 1%
12 ---> 12%
12.1 ---> 12.1%
12.12 ---> 12.12%
I'm using redux-form
I've tried react-native-text-input-mask and react-native-masked-text already, however, there is no similar functionality in these packages (in the first one there is something similar, but '%' is correctly displayed only if it is used before the number but this char should be after)
The best way here is to provide masking next to the input itself.
It highly depends on how do you use the Field component (do you even use it?).
You can try to use the format prop on the Field.
Or you can provide your own component to render a field and provide own format functionality:
const renderPercentagedInput = (field) => {
function onChange(evt) {
const value = evt.target.value;
const numbers = value.replace(/[^0-9.,]/g, '')
field.input.onChange(numbers + '%')
}
return (
<TextInput
{...field.input}
onChangeText={onChange}
/>
);
}

Ionic/Angular ion-datetime with condition

I have the following in Ionic and I'd like to let the user choose a datetime value but with one condition: If hour is equal to '21' then minutes must be '00' (not '30'), otherwise minutes value can be equal to '00' or '30'. Ideas?
<ion-datetime
hourValues="9,10,11,12,13,14,15,16,17,18,19,20,21 #hour"
[minuteValues]="hour != 21 ? '00,30' : '00'"
[(ngModel)]="time"
name="time"
required>
</ion-datetime>
It was not possible because the "minuteValue" is set first when u click on ion-datepicker to select date & time.
one way to achieve this is to compare your selected hour in .ts file and assign particular value based on hour to the minute like below.
In .html file.
<ion-datetime
hourValues="9,10,11,12,13,14,15,16,17,18,19,20,21 #hour"
minuteValues="0,30"
[(ngModel)]="time"
name="time"
displayFormat="MM DD,YYYY HH:mm"
(ionChange)="timeValue()"
required>
</ion-datetime>
In .ts file:
timeValue()
{
let hour = this.time.split('T')[1].split(':')[0];
let minute = this.time.split('T')[1].split(':')[1];
if(Number(hour) === 21)
{
minute = '00';
}
let date = new Date(this.timey);
date.setHours(Number(hour));
date.setMinutes(Number(minute));
console.log("------------"+date);
}

AngularStrap Typeahead randomly selects the display value instead of model value

I am using AngularStrap's Typeahead directive in several dropdowns and sometimes, the display value shows up as the selected value.
For example, if I want to show just the number as the selected value in the input field, sometimes both the number and the description are selected. Here is the relevant code :
<input type="text" class="form-control"
bs-typeahead
bs-options="x.num as (x.num > 0 ? x.num + '. ' + x.Description : '')for x
in crc.xList | orderBy: 'x.num'"
data-autoSelect="true"
data-limit="15"
ng-model="crc.newNum"
ng-model-options="{ debounce: 500 }"
ng-change="crc.getNumInfo(false, true)" />
Any help would be appreciated - thanks!
I think it is because of (x.num > 0 ? x.num + '. ' + x.Description : ''), I think angular replaces the empty string when x.num is 0 to the value, could you try to do (x.num > 0 ? x.num + '. ' + x.Description : 'test') instead and see if it fixes it ?

angulars js client side validation on phone number unable to combine regex formats

The following formats are allowed for the phone number
xxx-xxx-xxxx [x represents a digit]
xxx.xxx.xxxx
xxxxxxxxxx [digit ten times]
I have the working sample for the formats but I am unable to combine them in a single regex. How to combine them into a single regex?
"/^[1-9]\d{2}-\d{3}-\d{4}|^\d{10}$/"
"/^[1-9]\d{2}[.]\d{3}[.]\d{4}|^\d{10}$/"
"/^\d{10}$/"
My regex code in angular:
<div class="form-group" ng-class="{'has-error':userprofileForm.phone.$touched && userprofileForm.phone.$invalid && userprofileForm.extension.$touched && userprofileForm.extension.$invalid}">
<label for="profile-phone" class="control-label">{{'PHONE'|translate }}</label>
<div>
<input name="phone" type="text" class="form-control" ng-model="userprofile.phoneNumber" ng-pattern="/^\d{10}$/" required="required" />
<div ng-show="userprofileForm.phone.$touched && userprofileForm.phone.$invalid">
<span ng-message="required">Please enter phone number</span>
</div>
</div>
</div>
You can combine them like so:
ng-pattern="/^([1-9]\d{2}-\d{3}-\d{4})|([1-9]\d{2}\.\d{3}\.\d{4})|(\d{10})$/"
Just put every pattern in its own group with () and or them together with |.
Or more compact using a back reference (assuming your third case should also not start with a 0):
ng-pattern="/^[1-9]\d{2}([.-]?)\d{3}\1\d{4}$/"
RegEx breakdown:
^ // start of line
[1-9] // match '1', '2', '3', '4', '5', '6', '7', '8' or '9'
\d{2) // match 2 digits
( // begin capturing group 1
[.-] // match '.' or '-'
? // make the preceeding [.-] optional, so capturing group 1 matches '.', '-' or nothing.
) // end capturing group 1
\d{3) // match 3 digits
\1 // back reference: match what was matched by capturing group 1
\d{4) // match 4 digits
$ // match end of line
Note that due to the use of the back reference a mix like xxx.xxx-xxxx is correctly rejected.
Here's a similar post with various answers including $filter, regex etc.
Do check it out..
Also this handy online regex validator explains your regex might help validate the syntax.
Hope this helps.

Resources