format phone number using angularJs - javascript

How would I format a number like: (99) 9999-9999 into: 9999999999 using angularjs? someone told me to use phoneformat.js but I don't know how to implement it in my project

I'm not sure that you need anything special from Angular or any special libraries . . . just use the basic JS .replace() method and a little regex:
var sPhoneNum = "(99) 9999-9999";
var sFormattedPhoneNum = sPhoneNum.replace(/\D/g, "");
// sFormattedPhoneNum equals "9999999999"
The regular expression /\D/g matches all non-numeric characters, so it will strip out everything but the numbers.

so like talemyn said... the solution is simply to remove the unwanted char... the angular way to do it is via filter I guess... this is a jsfillde
with an example...
myApp.filter('phoneToNum', function() {
return function(input, scope) {
return input.replace(/\D/g, "");
}
});
now if you also want to revert it... use
phone filter

Try this:
formatLocal('US', phoneNumber)

I had an input field where I needed to get phone number from users but only the digits so that it's easy to index using phone number in the database. I used .replace on ng-keyup, so the non-digit characters gets removed as the user types.
in html
<input ng-keyup="formatNum()" ng-model='data.phone' placeholder="Phone Number" />
in controller
$scope.formatNum = function() {
if ($scope.data.phone)
$scope.data.phone = $scope.data.phone.replace(/\D/g, "");
};

Related

How to remove leading and trailing white spaces from input text?

I need to fix a bug in AngularJS application, which has many forms to submit data-
Every Text box in forms is accepting whitespaces(both leading and trailing) and saving them into the database. So in order to fix this I used ng-trim="true", it worked and data is getting saved correctly in the back-end.
Problem: Even after using ng-trim when I click on save/update, the form UI shows the text with white-spaces not the trimmed data. It shows correct data only when I refresh the page.
Can anyone guide me.. what will be the approach to fix this?
P.S. - I'm new to both JavaScript and Angular!
Thanks
Using trim() method works fine, but is used in newer browsers.
function removeWhitespaceUsingTrimMethod {
var str = " This is whitespace string for testing purpose ";
var wsr = str.trim();
alert(wsr);
}
Output:
This is whitespace string for testing purpose
From Docs:
(method) String.trim(): string
Removes the leading and trailing white space and line terminator
characters from a string.
Using replace() method – works in all browsers
Syntax:
testStr.replace(rgExp, replaceText);
str.replace(/^\s+|\s+$/g, '');
function removeWhitespaceUsingReplaceMethod {
var str = " This is whitespace string for testing purpose ";
var wsr = str.replace(/^\s+|\s+$/g, '');
alert( wsr);
}
Output:
This is whitespace string for testing purpose
Use string = string.trim() where string is the variable holding your string value.
When using reactive forms
this.form.controls['email'].valueChanges
.subscribe(x=>{
if(x.includes(' ')){
console.log('contains spaces')
this.form.controls['email'].setValue(x.trim())
}else{
console.log('does not contain spaces')
}
})

Check if a textbox contains numbers only

How to check if a textbox contains numbers only?
While googling I came across this. But I'm wondering if isNumeric can be used for this purpose or if there are more simpler ways of checking if a textbox has a numeric value.
var query = $('#myText').val();
if (parseFloat(query) == NaN) {
alert("query is a string");
} else {
alert("query is numeric");
}
You can check if the user has entered only numbers using change event on input and regex.
$(document).ready(function() {
$('#myText').on('change', function() {
if (/^\d+$/.test($(this).val())) {
// Contain numbers only
} else {
// Contain other characters also
}
})
});
REGEX:
/: Delimiters of regex
^: Starts with
\d: Any digit
+: One or more of the preceding characters
$: End
Regex Visualization:
Demo
If you want to allow only numbers, you can use input-number and pattern
<input type="number" pattern="\d+" />
using pure JS regular expression
var query = document.getElementById('myText').value;
var isNumeric=query.match(/^\d+$/);
if(isNumeric){/*...*/}else{/*...*/}
or using html5 control
<input type="number" name="quantity" min="1" max="5">
There're many ways, you can use isNaN
isNaN(VALUE);
You can also use regEx to verify numeric values.
console.log(/^\d+$/.test(VALUE));
Jquery provides generic util method to handle this.
handles numeric/float/hex
$.isNumeric( value )
Try: fiddle
You can match the value of text box against the numeric regression to check if it contains numbers only or not, Like below code...
if($('#myText').val().match(/^\d+$/)){
// Your code here
}

jQuery regexp validation

I would like to validate user input client side with a little jQuery function that is called onsubmit on my form. I want the field #fname (first name) to only allow a-z, A-Z and space. The return false is supposed to be stopping the form from submitting.
function validateregister(){
if (!($("fname") =~ [a-zA-Z ])) {
return false;
}
}
This is my HTML:
<input type="submit" value="Join now!" id="registersubmit" class="paddingoutline2" onsubmit="return validateregister()">
Of course, i'm going to validate the user input on the server side later on. When I submit the form, it gives me an "internal server error". This makes me think that I made an error in my function validateregister(). Is there anything wrong? If the I'm pretty new to jQuery so any help is appreciated.
Thanks!
What you want is
function validateregister(){
return /^[a-zA-Z ]+$/.test($('#fname').val());
}
Apart fixing the selector suggesting the use of the val and test functions, I took the liberty to change the regex :
^ and $ force the test to cover the whole string
the + requires at least one character
But are you aware that this regex might be too strict if you want people to type their real first name ? Yours, for example, would not pass...
You have to use regex this way:
function validateregister(){
var nameRgx = /[a-zA-Z]/;
var phoneRgx = /[0-9]/;
if (!nameRgx.test($("#fname").val())) {
return false;
}
if (!phoneRgx.test($("#phone").val())) {
return false;
}
}
And make sure to refer your elements with Either with # id notation or . class notation. In your code you are not referencing your elem in a proper way.
^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression;
also forces minimal matching when an expression might
match several strings within a search string.
More Info about Regex writing

javascript regular expression to test e-mail

I am trying to check the e-amil address like abc#example.co.uk or a.bc#eyample.com etc
and I am using regular expression like
[a-zA-Z0-9\._]+#[^.]+[a.zA-Z]+\.[a-z{2,5}]+
Can someone suggest how to correct it?
Thank you
See Using a regular expression to validate an email address
and you can try :
[a-zA-Z0-9.!#$%&'*+-/=?\^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*
This should work
Example
var sEmail = txtEmail;
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
If you make an input type email in new browsers it will validate to a certain level. It will only look for characters followed by a # and than a few characters after it.
Validating is to catch user mistakes not to make it harder for users to fill in your form.
I want to replace apostrophes "'" with "/" from string.
for example: var str ="te'xt";
want output like this "te/xt"

Validate first 2 characters of a textfield

I have a textbox whereby the user needs to input his/her mobile number. However I need to validate the first 2 numbers (characters) to make sure that the mobile number is in the correct format (as one of the validation rules).
The mobile number needs to start with any of the following 2 digits:
44xxxxxx
55xxxxxx
65xxxxxx
78xxxxxx
Can anyone tell me how it's possible to validate the first two characters number and check that they are either one of the options mentioned above?
EDIT
This is what I had tried but it did not work:
HTML
<input id="mob" name="mob" type="tel" placeholder="Enter your mobile number">
Validate
​
JS
var mobile_prefix = $('#mob').subsubstr(0,2);
$('#validate').click(function(){
if (mobile_prefix == 44||55||65||78) {
alert('correct');
}
else {
alert('incorrect');
}
});
​
I think .match() has what you're looking for. Just brush up on some regular expressions.
if (StringFromSelectField.match(/^(44|55|65|78)/)) {
//do something
}
Use substring from javascript
var FirstTwoLetters = TextFromYourInput.substring(0,2);
and then you can compare first two letters with your pattern.
Using a regular expression would probably be the easiest:
({phone number}).match(/^(44|55|65|78).*$/)
So first variable for input filed;Kind of my way;)
first check if that input is not empty and has 3 or more signs.
On the end is variable which I use on the end to allow form.submit().
If you want you can add before each getting val() $.trim(postcode.val()) != ''
var postcode = $('#post_code');
if(postcode.val() != '' && postcode.val().length > 2){
var shortPostCode = postcode.val().substring(0,2);
var validPostCode = /^(EH|KY)/;
if(!shortPostCode.match(validPostCode)){
postcode.after('<span class="error">Post code must start with EH</span>');
dataValid = false;
}
}

Categories