Hi am using angular 2 forms,
I have an inout field to key in users GSTIN value.
GSTIN format is XX-XXXXXXXXXX-X-X-X alphanumeric. What i need achieve is once the user keyin the values, I need to add a hyphen in to the keyed in value as per the format mentioned above.
HTML:
<custom-input [autocomplete]="false" [type]="'text'" [autocapitalize]="true" (change)="onGstinValChange($event)" (focusout)="onChangeGSTIN($event)"
[maxlength]="15" [formControl]="enterpriseDetailForm.controls['GSTIN']"
(ngModelChange)="mychange($event)"
[ngModel]="iban_no"></custom-input>
TS:
mychange(val) {
if (val) {
const self = this;
let gstin = val.split('-').join('');
if (gstin.length > 0) {
gstin = gstin.match(new RegExp('.{1,2}', 'g')).join('-');
}
console.log(gstin);
this.dataGstin = gstin;
}
}
With this function i can split every 2 values. Can someone help me on how i can achieve my format mentioned above? Thanks in advance.
Dont mix Reactive form approach with the Template drive form approach , just use one
so if you go with reactive form apporch then code will be
<custom-input [autocomplete]="false" [type]="'text'" [autocapitalize]="true" (change)="onGstinValChange($event)" (focusout)="onChangeGSTIN($event)"
[maxlength]="15" [formControl]="GSTIN"
></custom-input>
there is no need of (ngModelChange)="mychange($event)" [ngModel]="iban_no" as its template driven attributes
onGstinValChange($event){
let inputtext = $event.Traget.value;
///do code for adding - as per formate
enterpriseDetailForm.get('GSTIN').setValue(inputtext);
}
or just use reactive monitor change in value
ngOnInit() {
this.enterpriseDetailForm.get('GSTIN').valueChanges.subscribe(val =>
{
let gstin = val.split('-').join('');
if (gstin.length > 0) {
gstin = gstin.match(new RegExp('.{1,2}', 'g')).join('-');
}
enterpriseDetailForm.get('GSTIN').setValue(gstin );
}
, {emitEvent: false}));
}
html will be
<custom-input [autocomplete]="false" [type]="'text'" [autocapitalize]="true"
(focusout)="onChangeGSTIN($event)"
[maxlength]="15" [formControl]="GSTIN"
></custom-input>
Related
I want to enter an multiple field entered data in table with for loop
but i am getting an error in the post method.
error is
count(): Parameter must be an array or an object that implements Countable
controller code :-
$degree = $request->degree;
for($i=0;$i<count($degree);$i++){
$edu = new education;
$edu->degree = $request->degree[i];
$edu->clg = $request->clg[i];
$edu->yoc = $request->yoc[i];
$edu->save();
}
so, please suggest me what i can do.
Here not at all big problem,
you can not use count for the one value the array is required for
that i think that you have not been enterd dynamically many values it can be 0
so replace code in your controller:-
$degree = $request->degree;
if($degree > 0)
{
for($i=0;$i<count($degree);$i++){
$edu = new education;
$edu->degree = $request->degree[i];
$edu->clg = $request->clg[i];
$edu->yoc = $request->yoc[i];
$edu->save();
}
}
here i have used $degree if its value is greater then 0 that means
if it has value count grater then one then you can only go for loop and add value to database
otherwise it will be not go in for loop
React formik and react select package are I am using . I created on form that contains user can create new and Edit also working in same form. I have an one multi select field that field values are in array I want to change to string send to server on onSubmit. And also on update I want to get the string value convert array set to select field. I try it but cant found solution .please give me any ideas It helpful for me
codeSandbox:https://codesandbox.io/s/multipleselect-formik-3eqxp?file=/src/RegisterForm.js
Thanks for help
After getting the field value change the array to string on before submit. we want bind the change string value on field. It will be working fine for me.
Code Sandbox link :https://codesandbox.io/s/multipleselect-formik-3eqxp?file=/src/RegisterForm.js:657-844
function create(fields) {
console.log(fields);
const jobs = [];
fields.job.map((ele) => jobs.push(ele.value));
fields.job = jobs.toString();
console.log(fields);
}
i am not sure if this what you are looking for, but i did
function create(fields) {
fields.job = JSON.stringify(fields.job)
console.log(fields);
}
or
function create(fields) {
const jobs = [];
fields.job= fields.job.map((ele) => jobs.push(ele.value));
console.log(fields);
}
instead of
function create(fields) {
console.log(fields);
const jobs = [];
fields.job.map((ele) => jobs.push(ele.value));
const job = ("text => ", jobs.toString());
console.log(job);
console.log(fields);
}
I think you want to get the value from the array where the result should be
{name: "111", fatherName: "222", job: ["enginner", "painter"] }
function create(fields) {
const amendedFields = {
...fields,
job: fields.job.map((ele) => ele.value) // extract value from object, ["enginner", "painter"]
}; // not mutating the current fields object, copy it and mutate the new one.
console.log("old", fields);
console.log("new", amendedFields);
}
Iām new to Vue.
I would like to know if it is possible to update the input value after running a custom validation in Vuelidate. I have an input field for postcode. I want to return the postcode with the correct format in case the user forgets to put a whitespace, and update the input field with the correct value, e.g.
user input = XXXXXX
returned output = XXX XXX
Sample code
export default {
...
validations: {
postcode: {
required,
maxLength: maxLength(10),
validatePostcode: (value) => {
const result = customValidators.validatePostcode(value);
if (result !== false) {
if (result !== value) {
// UPDATE THE INPUT VALUE HERE WITH THE CORRECT POSTCODE FORMAT
}
return true;
}
return false;
}
}
}
...
}
I changed the arrow function declaration to a function shorthand declaration. I'm now able to access the component object and change the input field value via the Vuelidate model. Thanks to this: https://github.com/vuelidate/vuelidate/issues/237 š
Hi i am using Angular8 with Bootstrap, here i have used reactive forms, when i check on Make Default checkbox, then values present in Flowers row (Mail, Electronic,Delivery and Receipent)should be copied same to rest rows.
If the fax number format is not proper, how to show error message just below particular row recepient.
Ts:
checkAll(ev) {
const control = <FormArray>this.exampleForm.get("printList");
if (!this.all) {
this.printListArray.forEach(x => (x.value = false));
control.patchValue(this.printListArray);
} else {
this.printListArray.forEach(x => (x.value = true));
control.patchValue(this.printListArray);
}
console.log(control.value);
}
isAllChecked() {
this.all = !this.all;
}
DEMO
Your code should work more like the following
checkAll(ev) {
const control = <FormArray>this.exampleForm.get("printList");
console.log(this.all);
if (this.all) {
this.all = false;
this.printListArray.forEach(x => (x.electronics = false));
control.patchValue(this.printListArray);
} else {
this.all = true;
this.printListArray.forEach(x => (x.electronics = true));
control.patchValue(this.printListArray);
}
}
The main difference is that instead of changing the value field of x I'm changing the electronics fields, so when you are patching the form latter on, this.printListArray will have the appropriate data in the appropriate state.
In the implementation that I'm suggesting you will be able to toggle all checboxes in the row Electronics
Keep in mind that the printListArray is not an array form FormGroup/FormControl, its an array of regular objects, so the field value that usually exists in the FormControl is not present.
I am trying to check the email validity (when the user start typing onkeyup), then if the email is valid I push it into an array of unique emails; however, I stop pushing to the array once it reaches a certain number, in my case it's 3.
<textarea (ngModelChange)="onKeyUp($event)"></textarea>
onKeyUp(ev) {
let finalEmailList = []
this.finalEmailList = [];
this.numberOfUsers = 3;
let emails = ev.replace(' ', '').split(/,| /);
emails.forEach(email => {
if (this.validateEmail(email)) {
//If the email has a valid format, the push it to the array
finalEmailList.push(email);
//it's a lodash function to clean the array an keep only unique emails in the array
this.finalEmailList = _.uniq(finalEmailList);
if (this.finalEmailList.length <= this.numberOfUsers) {
this.numberOfUsers -= this.finalEmailList.length;
}
}
})
}
//returns true if the email has a valid format
validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
The issue:
I believe it's a wrong way to do it as on each and every letter printed from the keyboard everything runs again and again, resetting variables, running for loops, etc...
Also the value returned for this.numberOfUsers is not correct.
If you want the email address to be complete before validating, validating onBlur as others have suggested may be your best course of action.
Another option is to continue listening for onKeyUp, but only trigger validation if the key is a specific trigger key.
Example:
onKeyUp(event) {
if ([13, 188].includes(event.keyCode)) {
validateEmails()
}
}
In this example, 13 and 188 are the key codes for Enter and comma, respectively.
If you want to apply a check on different entries, the simplest solution would be to have one input per email. Not sure it'll fit your need as you haven't say whether you want to stick with a textarea or not but here's my idea:
Create a form containing a formArray with all the required emails.
this.emailsForm = this.fb.group({
emails: this.fb.array(this.getEmailsFormGroup())
});
Here's how to create the formArray:
getEmailsFormGroup() {
const emailsForms: FormGroup[] = [];
for (let i=0; i<this.nbEmails; i++) {
emailsForms.push(this.fb.group({
email: ['', [emailValidator()], []]
}));
}
return emailsForms;
}
Here we're taking advantage of the validators array and calling a custom validator emailValidator, which is defined like that:
const emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
export function emailValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
return emailRegex.test(control.value) ?
null :
{ 'not-email-like': { value: control.value } };
};
}
Full component code (TS):
#Component({
selector: 'app-emails',
templateUrl: './emails.component.html',
styleUrls: ['./emails.component.css']
})
export class EmailsComponent implements OnInit {
nbEmails = 3;
emailsForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.emailsForm = this.fb.group({
emails: this.fb.array(this.getEmailsFormGroup())
});
}
getEmailsFormGroup() {
const emailsForms: FormGroup[] = [];
for (let i = 0; i < this.nbEmails; i++) {
emailsForms.push(this.fb.group({
email: ['email-' + i, [emailValidator()], []]
}));
}
return emailsForms;
}
}
HTML:
Please enter the {{ nbEmails }} required email{{ nbEmails > 1 ? 's' : '' }}
<form [formGroup]="emailsForm">
<div formArrayName="emails">
<div *ngFor="let email of emailsForm.controls['emails'].controls; let i=index" [formGroupName]="i">
<input
type="text"
formControlName="email"
>
</div>
</div>
</form>
<hr>
<div>
VALID? {{ emailsForm.valid }}
</div>
<hr>
<div>
<pre>
{{ emailsForm.value | json }}
</pre>
</div>
Here's a working version on Stackblitz:
https://stackblitz.com/edit/angular-lxltri?file=src%2Fapp%2Femails%2Femails.component.ts
Notice that you have access to the property valid of the form so you know when the X emails are in a valid state.
What I understand is, you have a textarea, where user can enter multiple emailIds. You want to validate each and add into an array.
First, you should not subscribe to ngModelChange, instead subscribe to blur event. Which means only when user moves out of the field, you split the input value based on comma separator and validate each.
Second, you can also separate the input value based on /n i.e. line change. using this .split(/\r?\n/)
This way you don't have to clean array, loop through input field value every time user enters something.
I rather have a single input and a add button. Take the email input and run the logic on click event of add button.That will make sure code runs only when needed and provides user with a better UX. Something like git has done with user profiles
Reference UI