How to validate mobile number for countries in angular?
You need to incorporate literal parenthesis in your regex which can be there optionally and since they have special meaning hence you need to escape them in your regex.
Seeing your last mobile number 09876543210
, it seems you optionally want to support zero before a number if there is no country code, so you can have zero in alternation for your country code part.
And last, like you don't want to support a number only having all zeroes, you can have a negative look ahead (?!0+$)
in your regex. Your updated regex becomes,
^(?!0+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$
Live Demo
Also, you if you don't want to support numbers having only same digits like 2222222222
or 5555555555
then your negative look ahead needs to be written as (?!(\d)\1+$)
and your regex will become,
^(?!(\d)\1+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$
Demo for this updated regex
Another way for validating mobile numbers can be, you replace everything that is not a digit and also get rid of all leading zeroes in your number, then what remains will be pure mobile number which you can further validate. But there may be certain disadvantages there as it may become a bit hard to figure out the country code and if the number is really valid. Because certain numbers may be less than ten digits and may actually be invalid but they may be valid if they belong to a country like Singapore which has I guess 8 digit numbers. And same with countries having eleven digits local number might trouble you.
How to validate the country code with + sign in Angular 7?
Try a regex staring with +
and has the desired number of digits
let regex = /^[+]\d{12}$/; // enter the total number if digits you want
let correct = '+911234567890'let inCorrect = '911234567890'
console.log(regex.test(correct))console.log(regex.test(inCorrect))
How to get country code and phone number separately and validate length of the ph number based on country code in javascript?
I have Installed these two libraries.
1) "ngx-mat-intl-tel-input": "^3.0.0",
2) "libphonenumber-js": "^1.7.51"
it works perfectly for me.. I can able to get dialCode and phone number seperatly in this library.And its validating length also..
(Angular2/4/5/6) How to validate length of international phone numbers according to country
This is my custom solution. It works fine on my solutions.
Please install intl-tel-input to your project
npm i intl-tel-input --save
Then create a IntlTelInputComponent
component as follows.
intl-tel-input.component.ts
import {
AfterViewInit, Component, ElementRef, EventEmitter, Input, Output, ViewChild, forwardRef, Renderer
} from '@angular/core';
import 'intl-tel-input';
import * as jQuery from 'jquery';
import { NG_VALUE_ACCESSOR, ControlValueAccessor, } from '@angular/forms';
export interface ITimeInputFieldChanged {
value: string;
extension: string;
numberType: string,
valid: boolean;
validationError: any
}
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => IntlTelInputComponent),
multi: true
};
const noop = () => {
};
@Component({
selector: 'intl-tel-input',
templateUrl: './intl-tel-input.component.html',
styleUrls: ['./intl-tel-input.component.scss'],
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class IntlTelInputComponent implements ControlValueAccessor {
@Input() fullValue: string;
@Output() fullValueChange = new EventEmitter<ITimeInputFieldChanged>();
@Input() id: string;
@Input() intlOptions = {
initialCountry: 'no',
formatOnDisplay: true,
separateDialCode: true,
onlyCountries: ['no', 'be']
};
@Input() value: string;
@Output() valueChange = new EventEmitter<string>();
@Output() valueBlur = new EventEmitter<string>();
@Output() valueFocus = new EventEmitter();
@ViewChild('intlInput') intlInput: ElementRef;
private extension: string;
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
constructor(
private _renderer: Renderer) { }
onInputChange(value: string) {
const intlInput = jQuery(this.intlInput.nativeElement)
this.value = value;
this.valueChange.emit(value);
this.fullValue = intlInput.intlTelInput('getNumber');
this.extension = intlInput.intlTelInput('getSelectedCountryData').dialCode;
const validationErrorCode = intlInput.intlTelInput('getValidationError');
let validationMessage = 'VALID';
switch (validationErrorCode) {
case 1:
validationMessage = 'INVALID_COUNTRY_CODE'
break;
case 2:
validationMessage = 'TOO_SHORT'
break;
case 3:
validationMessage = 'TOO_LONG'
break;
case 4:
validationMessage = 'NOT_A_NUMBER'
break;
case 5:
break;
default:
validationMessage = 'VALID'
break;
}
this.fullValueChange.emit({
value: value,
extension: this.extension,
numberType: intlInput.intlTelInput('getNumberType'),
valid: intlInput.intlTelInput('isValidNumber'),
validationError: validationMessage
});
// this.writeValue(this.fullValue);
}
onBlur(value: string) {
this.valueBlur.emit(value);
}
onFocus() {
this.valueFocus.emit();
}
writeValue(value: any): void {
if (value && (value !== this.value)) {
this.fullValue = value;
setTimeout(() => {
const phoneInput = jQuery(`input#${this.id}`);
phoneInput.intlTelInput('setNumber', this.fullValue);
}, 100);
}
}
registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
registerOnTouched(fn: () => any): void { this.onTouchedCallback = fn; }
setDisabledState?(isDisabled: boolean): void {
throw new Error('Method not implemented.');
}
}
intl-tel-input.component.html
<input #intlInput class="form-control"
[appIntlTelInput]="intlOptions"
[id]="id"
[ngModel]="value"
(ngModelChange)="onInputChange($event)"
(blur)="onBlur($event)"
(focus)="onFocus()"
>
intl-tel-input.component.scss
:host /deep/.intl-tel-input{
display: block;
.country-list{
overflow-y: auto;
}
}
intl-tel-input.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import 'intl-tel-input';
import * as jQuery from 'jquery';
@Directive({
selector: '[appIntlTelInput]'
})
export class IntlTelInputDirective implements OnInit {
@Input('appIntlTelInput') appIntlTelInput: any;
constructor(private el: ElementRef) { }
ngOnInit() {
// jQuery.fn.intlTelInput.loadUtils('https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.12/js/utils.js');
// jQuery.fn.intlTelInput.loadUtils('/intl-tel-input/build/js/utils.js');
jQuery.fn.intlTelInput.loadUtils('assets/js/utils.js');
jQuery(this.el.nativeElement).intlTelInput(this.appIntlTelInput);
}
}
Usage inside a form
<intl-tel-input formControlName="Mobile" ></intl-tel-input>
Hope this will solve your problem. It can validate any international mobile number as you want.
Related Topics
How to Change Image and Text Color When Clicking Using React-Native
React-Redux State Lost After Refresh
How to Print Image from Browser Using JavaScript
React Hooks Error: Hooks Can Only Be Called Inside the Body of a Function Component
Background-Image in React Component
Bootstrap 4 Display Dropdown Submenu on the Right Side
Angular [Innerhtml]: How to Render Additional Elements Inside an Element With [Innerhtml] Directive
How to Get Width of (Dom) Element in Angular2
Check If a String Is HTML or Not
Get Docx File Contents Using Javascript/Jquery
Button Enabled and Disabled Based on Checkbox Is Checked or Not
Javascript Generate Random Numbers Without Repeating
Sticky Header Smoothing Scroll Down
Jquery Wait Until Ajax Call Has Got Data Before Displaying
One Time Page Refresh After First Page Load