ng-pattern to dissallow email, url and telephone numbers - javascript

Hi I want to validate a textangular box which will have a lot of text, but I don't want to allow telephone numbers, email ids or any URLs in this text box. I want to show the error message as the email/telephone/url if mentioned in the text box as well and say that is not allowed.
Using ng-Pattern, please tell me what regex to use to allow this.
<div class="form-group">
<div class="col-sm-6 col-md-8">
<label for="inputjobDescription" class="control-label lightfont">Description</label>
<div text-angular ng-model="job.Description" name="description" ng-pattern="/^((([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6}))\n?)*$/" ng-minlength="100" ta-min-text="100" required>
</div>
<p ng-show="jobform.description.$invalid && !jobform.description.$pristine && !jobform.description.$error.pattern" class="help-block">Can you be a bit more elaborate(atleast 100 characters) , please?<br> Don't write your emailID, telephone number or any URL.</p>
</div>
</div>
My current ng-pattern is as follows
ng-pattern="/^((([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6}))\n?)*$/"

This doesn't look like a good spot for a regex. A regex would probably be too complicated here.
I would suggest to use a custom validator here and try it the other way around:
Compare the given text with 3 different regexes:
Is there any phonenumber in it ?
Is there any email in it ?
Is there any hyperlink in it ?
Only if ALL these three (better manageable) expressions FAIL you are ok and return that the expression is valid.
In this case you can use three standard regexes from a casual google search instead of inventing some mindblowing super-regex if you know what i mean.

Related

Regex problems with angularjs

I am trying to use a regular expression to validate an email address. It does not seem to be doing any validation at all. When I load the page the Submit button is disabled because of the $pristine but as soon as I type a letter the button becomes enabled. Also I am aware that the regex is only accepting upper-case at the moment. The following code is my form:
<form name="myForm" ng-hide="email" >
Insert Email : <br/>
<input type="text" name="email" ng-pattern="/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]
{2,4}$/" ng-model="insert_email" required>
<br/>
<button ng-hide="email"
type="submit"
ng-disabled="myForm.email.$pristine || myForm.email.$invalid">Submit</button>
</form>
I am not sure but I think the problem may lie with the regex itself.
take out the email in myForm.email.$pristine and in myForm.email.$invalid
to look like:
myForm.$pristine
and
myForm.$invalid
also try with ng-required instead of required
It seems to be two things. It looks like the ng-pattern expects an expression instead of a string attribute.
So you need to wrap it in a string if you want to use an inline expression.
Like so:
ng-pattern="'^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}$'"
Also, there seems to be some issues with your regex. I changed it to this:
ng-pattern="'^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'"
It seems to work.
Plunker Demo

Email validation with particular extensions?

form code:
<form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" >
<p class="email">
<label for="budget">Expected Budget :</label>
<input type="text" name="budget" id="budget"/>
</p>
<p class="submit">
<label for="download" id="freetrail">Download 30 day free trial</label>
<input type="submit" value="Submit" />
</p>
</form>
i want to validate email-ids with the extension which are checked in the above image and block rest of the email-id extensions using javascript..any help would be appreciated??
(\w+\.)*\w+#(\w+\.)+[A-Za-z]+
this regex is email check basic.
you may use regex for this case, follow regex:
((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)
okay , get all the values of checked items in an array (at least this much you should have been able to do by now)
now let the array be ["com","net"]
var arr = ["com","net"];
var str = arr.join("|")
var re = new RegExp("^\w+#\w+\.("+str+")$");
console.log(re);
the regex I have used is the most basic of all, you can change it according to your needs. Another answer on SO suggests "^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" to be a more complete email validator. So you can change your second last line to :
var re = new RegExp("^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.("+str+")$");
this code will give you the regex you need to validate your email.
Now you can simply do regex test to see which emails pass your validation.
happy coding!
You can also use above regex ( aelor's )as
[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.(COM|ORG|BIZ|CO)
include your all extentions using pipe separator .

ng-pattern is not working for number input

I am trying to implement input number field which will allow positive or negative numbers.
I have used "/^0|[1-9]\d*$/" regex expression for ng-pattern.
But it is not working.For character input it is not showing any error.
I have pasted my code here.
Update
I don't want to make this field as required.I just want only number validation(charters are not allowed).
There are a couple of problems with your code:
The pattern /^0|...$/ is interpreted as /(^0)|(...$)/. So, your pattern will accept any string that either begins with 0 (no matter what follows) or ends with any digit in [1-9] (optionally followed by any number of digits).
The correct pattern is: /^(0|[1-9][0-9]*)$/ (note that \d will match more characters than [0-9], e.g. arabic digit symbols etc).
The input elements of type number are handled in the following way by the browser:
If their content is not a valid number, then their value property is set to ''.
Thus, entering 1w3 will cause the value to be an empty string, so then pattern will not be applied.
You should use an input element of type text.
(This is not directly related to your question, but I noticed in your fiddle, you were using <form>.<input>.$invalid, instead of the (probably) intended <form>.<input>.$valid.
$invalid is a property of the FormController only.)
Based on the above, your code should look more like this:
<input type="text" name="price_field" ng-model="price"
ng-pattern="/^(0|[1-9][0-9]*)$/" />
(For accepting negative numbers as well, change ng-pattern to /^(0|\-?[1-9][0-9]*)$/.)
See, also, this short demo.
(UPDATE: The demo has been updated to illustrate the differences between number- and text-fields and between different patterns.)
Why do not use required with min. So we can write:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number"
ng-model="price"
ng-init="price=0"
name="price_field"
min="0"
required
>
<span ng-show="myForm.price_field.$error.required ||
myForm.price_field.$error.min">Not a valid number!</span>
<input type="submit" value="submit" />
</form>
</div>
Demo Fiddle
Howevewr if you still want to use pattern, remove type="number". I'm not sure but sounds like type number has own pattern, this is a reason why it doesn't work.
Here is 2nd Demo Fiddle
used htm5 pattern for input number only
<input type="number" name="country_code" pattern="[0-9]" >
http://www.w3schools.com/tags/att_input_pattern.asp

Angularjs Form/Field validation using JavaScript function without directives

Is there a way to validate a field in angular without using a directive?
For example: I want to make following validation on an input field.
If field is empty we should show "Field must contain a value" message.
if field contains alpha Numeric characters we should show "Field can contain only digits".
An EVEN number - message to the user "Value must be an even number".
I want to make following validation in a call to JavaScript function.
I googled around and saw that there is a way to use ng-valid and $error , however I was not managed to make it work.
Code below is according to one of the answers I got:
<div ng-app>
<form name='theForm' novalidate>
<input type='text' name='theText' ng-model='theText' ng-pattern='/^[0-9]+$/'/>
<span ng-show='theForm.theText.$error.pattern'>Field can contain only digits</span>
<span ng-show='theText.length<1'>Field must contain a value</span>
<span ng-show='theText%2!=0&&document.getElementsByName("theText").value!=""&&!theForm.theText.$error.pattern&&!theForm.theText.$pristine'>Value must be an even number</span>
<br/><input type='submit' value='Submit' />
</form>
I want to take what inside the last [span] and put inside a JavaScript function in order to make it more generic and eventually change only JS and not the HTML when conditions are changing
Can someone please advise? a working example would be great.
I'm surprised no one has mentioned ui-validate
$scope.isOdd = function($value){
return $value % 2;
}
...
<form name="myform">
<input ng-model="myVal" name="value" required
ng-pattern="/^[0-9]*$/" ui-validate=" 'isOdd($value)' "></input>
<pre>{{myform.value.$error|json}}</pre>
</form>
Doesn't get any simpler than that, and it's PROPER AngularJS validation (not silly watches)
Here's a working demo
Take a look at the angularjs form documentation - http://docs.angularjs.org/guide/forms . In general, it is based on the HTML5 attributes like required, min, max, etc.
To get, for example, your first requirement done - "an empty field should show "Field must contain a value" message, yo uwould do something like that:
<input type="text" ng-model="user.name" name="uName" required /><br />
<div ng-show="form.uName.$invalid">
<span ng-show="form.uName.$error.required">Field must contain a value.</span>
</div>
For digits only field you can use the pattern attribute with a matching regular expression (example: http://www.wufoo.com/html5/attributes/10-pattern.html).
For even number validation, I'm not sure - I think you'd have to go with custom validation for that (meaning you'd have to create a directive) or use the pattern attribute somehow.
Last but not least - remember to add novalidate to the <form> tag. Otherwise the browser will try to validate your fields as well and you don't want that:
<form ... novalidate>
...
</form>
I know the question is old and I know you didn't want a directive but you may consider using a directive if it's "Angular" way... Well here is my Angular-Validation. I made a project on Github and I think that it just rocks compare to whatever is/was available...I based myself on the excellent Laravel PHP Framework and made it available under Angular... It is so crazy simple, you need 2 lines 1 line of code, 1 line for the input, 1 line for error display, that's it... never more and never less!!! Enough said, let's give some examples:
<!-- example 1 -->
<label for="input1">Email</label>
<input type="text" validation="email|min_len:3|max_len:25|required" ng-model="form1.input1" name="input1" />
<!-- example 2 -->
<label for="input2">Alphanumeric + Exact(3) + required</label>
<input type="text" validation="alpha|exact_len:3|required" ng-model="form1.input2" name="input2" />
So I can define whatever amount of validation rules (already 25+ type of validators) which I want in a simple directive validation="min_len:2|max_len:10|required|integer" and the error message will always display in the next <span> Don't you guys like it already? 1 line of code for your input, 1 line of code for the error display, you can't be simpler than that...oh and I even support your custom Regex if you want to add. Another bonus, I also support whichever trigger event you want, most common are probably onblur and onkeyup. Oh and I also support multiple localization languages via JSON external files. I really added all the imaginable features I wanted into 1 crazy simple directive.
No more clustered Form with 10 lines of code for 1 input (sorry but always found that a little extreme) when the only thing you need is 2 lines, no more, even for an input with 5 validators on it. And no worries about the form not becoming invalid, I took care of that as well, it's all handled the good "Angular" way.
Take a look at my Github project Angular-Validation... I'm sure you'll love it =)
UPDATE
Another candy bonus! To make an even more smoother user experience, I added validation on timer. The concept is simple, don't bother the user while he's typing but do validate if he makes a pause or change input (onBlur)... Love it!!!
You can even customize the timer as per your liking, I've decided to default it to 1 second within the directive but if you want to customize you can call as for example typing-limit="5000" to make a 5 sec. timeout. Full example:
<input type="text" ng-model="form1.input1" typing-limit="5000" validation="integer|required" name="input1" />
<span class="validation text-danger"></span>
UPDATE #2
Also added input match confirmation validation (ex.: password confirmation), here is a sample code
<!-- input match confirmation, as for example: password confirmation -->
<label for="input4">Password</label>
<input type="password" name="input4" ng-model="form1.input4" validation="alpha|min_len:4|required" />
<label for="input4c">Password Confirmation</label>
<input type="password" name="input4c" ng-model="form1.input4c" validation="match:form1.input4,Password|required" />
UPDATE #3
Refactored the directive so that the requirement of having a <span> to display the error is unnecessary, the directive now handles it by itself, see the code change reflected on top.
DEMO
Added a live demo on Plunker
Well you can try to create a func
<span ng-show='isEven(theText)'>Value must be an even number</span>
$scope.isEven=function(data) {
if(data) {
return data%2===0
}
return true;
}
The method can either be defined on the current controller scope or on $rootScope.
Not a very angular way, as directives would be better but i think it would work.

How can I validate a full name input in a form using javascript?

I would like to write a function to validate a full name input in a form with Javascript:
a single word will be ok, a string with some blank character among name surname, middle name too, but I do not want any digit.
Any suggestion?
There are several ways to write this, but, simply, the regular expression
/^[a-zA-Z ]+$/
should work for you. It will find any combination of alpha characters and spaces but no digits.
Edit to add the information from my comment, which I feel is important:
You may also wish to add the apostrophe and hyphen between the brackets, since Irish and Italian names include the former (O'Donnell, D'Ambrosio) and some folks have hyphenated last names (Claude Levi-Strauss, Ima Page-Turner, etc.).
This would result in the following expression:
/^[a-zA-Z'- ]+$/
Try this RegEx for maximum compatibility:
Don't forget to escape the single quote-marks (') if you put this in a JavaScript string enclosed with single quotes.
^(?:((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$
Example:
function checkName(eid){ alert(/^(?:((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$/.test(document.getElementById(eid).value)? 'Congratulations! You entered a valid name.' : 'Sorry, You entered an invalid name. Please try again.');};
*
{
color:#535353;
font-family:Arial, Helvetica, Sans-Serif;
}
input:valid
{
background-color: #DEFFDF;
}
input:invalid
{
background-color: #C7D7ED;
}
<form action="#" method="post" onsubmit="checkName('full_name');return false;">
<label for ="full_name">Your Name: </label>
<input type="text" name="full_name" id="full_name" maxlength="85" pattern="^(?:((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=##$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$" title="Please enter your FULL name." style='width:200px;height:auto;' required>
<br><br>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
I would suggest not putting so much effort in validating data via JS. If a user has JS disabled, you will end up with some data you don't want on database.
Validate it via the server side.
Now, regards your question, I would try with regular expressions.

Categories