how to use regular expression in javascript - javascript

var pattern=/[A-za-z0-9]/;
if((fs.value||ls.value||ad1.value||ad2.value||pc.value||city.value||email.value)!=pattern)
{alert("fields not entered");
return false;}
else
return true;
Even after entering all the fields in the form, I get alert message "field not entered. Here fs,ls,ad1,ad2,email,pc and city are form field values

You need to take the values from those fields and run them thru the regex matching tool while passing the regex to that method.
var pattern=/[A-za-z0-9]/;
"string to check against regex pattern".match(pattern);
See more here

Related

Regex to extract arguments passed into string '#substr( , , )'

we have a text input where the user can enter some text and apply some functions on top of the text like ( substr , replace ) etc. For example user can enter the text "hello" in the text input and can apply the substring function ( #substr(hello, 'startIndex', 'length'))and can mention the start index and the length etc.
Need to use the regex to extract the values passed into the #substr function for validating the mandatory fields. For example 'start index' and 'length' is required when the user selects the substr function.
Below are the different scenarios and its expected output .
#substr(hello,1,3) ---> ['hello','1','3']
#substr($(sometext),1,3) ---> ['$(sometext)','1','3']
#substr(#trim(hello),1,3) ----> ['#trim(hello)','1','3']
#substr(#replace(hello-world,hello,hi),1,3) ---> ['#replace(hello-world,hello,hi)','1','3']
As from the above examples need to extract the arguments passed into the #substr function as array elements.
Tried this regex
/#substr\((.*?),(.*?),(.*?)\)/g
This fails when we have a nested functions like this - #substr(#replace(hello-world,hello,hi),1,3)
You could use the below regex with capturing groups.
#(\S+?)\((.*)\,(\d+),(\d+)\)
For nested matching, it is not impossible, but much complex in regex. The easy approach should be avoiding regex and using js code for nested matching.
This regex can solve your problems, if the string takes up an entire line, but if you enter comma commands in the second argument, it will fail, this is a very complex problem to solve with simple regex. I think you're knocking on the compilers' door.
regex = /^#substr\((.*),(.*),(.*)\)$/;
text = "#substr(#replace(hello-world,hello,hi),1,3)";
console.log(regex.exec(text));
If you're trying to get the length of user input or index, you could put all the desired methods inside a function or multiple functions that call be called on button-click.
https://www.bitdegree.org/learn/javascript-input
I may be misunderstanding but if I take one of your examples:
#substr(hello,1,3) ---> ['hello','1','3']
When I run
str = "hello world"
str.substring(1,3) --> I get "el" (not "hello", "1", "3")
Get some text:
var firstName = document.getElementById("firstName").value;
var age = document.getElementById("age").value;
Click a button to call your function.
function doSubstringStuff(textValue, subString_mode) {
if subString_mode == "length" {
return textValue.length;
}
OR
Validate the length matches your criteria.
if (textValue.length > 10) {
alert("The name must have no more than 10 characters");
Or Perform other tasks, determined by the argument "mode"
else if subString_mode == "integer_test"{
if (isNaN(textValue) || age < 12 || age > 100){alert("The age must be between numbers 12 and 100")};

javascript validation not working for only alphabetic values

I have used a javascript validation function to validate it. I've used it to see whether the text entered to the html textbox is alphabetic(No numeric characters allowed). The function is called during onkeyup and onblur. The only problem is even when numeric values or special characters are typed in the validation doesn't work. If I leave the field blank then it works(Displays that the field is left blank). Here's my javascript code:
function isAlphabetic(x,y){
var exp = /^[a-zA-Z]+$/;
var a = document.getElementById(y).value;
if(a=="" || a== null){
document.getElementById(x).innerHTML = "You cannot leave this feild empty";
return;
}
else if(a!="" && a!= null){
if(y.match(exp)){
document.getElementById(x).innerHTML = "";
return;
}
else{
document.getElementById(x).innerHTML = "Only enter alphabetic characters allowed";
return;
}
}
else{
return;
}
If you use y as an id of element, I suppose you shouldn't check it with your regexp. Instead you should check a:
if(a.match(exp)) {
You don't need JavaScript anymore for any of this. Use the pattern attribute on the input field and the browser won't let the user enter anything that doesn't match, and use required to prevent submitting the form with an empty value.
Also, do you really want only ASCII letters? (are spaces allowed? how about non-ASCII letters such as "é"?)

validation illegal characters going through with valid

Why does my javascript form validation allow illegal characters through when valid characters are entered alongside them?
Here is my script
//Address Validation
var Address1 = document.forms ["tiptopform"]["Address1"].value;
var message="Please enter a valid Address" ;
var problem=false;
var patt1=new RegExp (/[A-Za-z0-9-]/);
var result = patt1.test(Address1);
if (result){
message=message;
problem=true
}
if (problem) {
alert (message)
}
I have tried reversing the true and false variable but that as expected only reverses the problem.
You are testing if you regular expression can be found within prvided address.
You want to match whoel adress and tets if it conatins only specific characters, use:
/^[A-Za-z0-9-]*$/
that is from start to end any number of those characters
sidenote: /regexp/ is a waz to write dont regular expression, zou don't have to call new RegExp or you can provide this regualr expression as string then use
new RegExp ("^[A-Za-z0-9-]*$");

Form validation of numeric characters in JavaScript

I would like to perform form validation using JavaScript to check for input field only to contain numeric characters.So far, the validation checks for the field not being empty - which works fine.However, numeric characters validation is not working.I would be grateful for any help.Many thanks.
<script type="text/javascript">
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["univer_number"].value
if (x==null || x=="")
{
alert("University number (URN) field must be filled in");
cdp_form.univer_number.focus();
return false;
}
else if (is_valid = /^[0-9]+$/.test(x))
{
alert("University number (URN) field must have numeric characters");
cdp_form.univer_number.focus();
return false;
}
}
</script>
<input type ="text" id="univer_number" maxlength="7" size="25" name="univer_number" />
Rather than using Regex, if it must only be numerals you can simply use IsNumeric in Javascript.
IsNumeric('1') => true;
IsNumeric('145266') => true;
IsNumeric('abc5423856') => false;
You need invert your regular expression (add ^ inside [0-9]):
/^[^0-9]+$/
Your test condition is a bit strange:
else if (is_valid = /^[0-9]+$/.test(x))
Why have the redundant comparison to is_valid? Just do:
else if (/^[0-9]+$/.test(x))
Though the regex you are using will match numerals and only numerals - you need to change it to match anything that is not a numeral - like this /^[^0-9]+$/.
Better yet, get rid of the regex altogether and use IsNumeric:
else if (!IsNumeric(x))
On your line that says else if (is_valid = /^[0-9]+$/.test(x)), you're doing a simple assignment instead of testing that it is actually matching the regex.
Your pattern will still accept this input <b>##$##123 or ad!##12<b>. Use this pattern I created:
/[a-zA-Z-!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?]/
This pattern will check if it is alphabetic and special characters.
You need to test for the negation of the RegExp because you want the validation to alert upon failure, so just add ! in front of it:
else if (is_valid = !/^[0-9]+$/.test(x))
See example →
I know this is an old post but I thought I'd post what worked for me. I don't require the field to be filled at all but if it is it has to be numerical:
function validateForm()
{
var x=document.forms["myformName"]["myformField"].value;
if (/[^0-9]+$/.test(x))
{
alert("Please enter a numerical amount without a decimal point");
myformName.myformField.focus();
return false;
}
}

JavaScript Regular Expression Email Validation [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
How can I validate an email address using a regular expression?
(79 answers)
Closed 8 years ago.
This code is always alerting out "null", which means that the string does not match the expression.
var pattern = "^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$";
function isEmailAddress(str) {
str = "azamsharp#gmail.com";
alert(str.match(pattern));
return str.match(pattern);
}
If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\\w'.
Alternatively, define it as a regular expression:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
BTW, please don't validate email addresses on the client-side. Your regular expression is way too simple to pass for a solid implementation anyway.
See the real thing here: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
this is the one i am using on my page.
http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/
/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
I've been using this function for a while. it returns a boolean value.
// Validates email address of course.
function validEmail(e) {
var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return String(e).search (filter) != -1;
}
Sometimes most of the registration and login page need to validate email. In this example you will learn simple email validation.
First take a text input in html and a button input like this
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
<script>
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
you can also check using this regular expression
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
<script>
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
Check this demo output which you can check here
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>
if email invalid then give alert message , if valid email then no alert message .
for more info about regular expression
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
hope it will help you
You may be interested in this question (or this one), which highlights the fact that identifying valid email addresses via regexps is a very hard problem to solve (if at all solvable)
with more simple regex
Here it is :
var regexEmail = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("txtEmail");
if (regexEmail.test(email.value)) {
alert("It's Okay")
} else {
alert("Not Okay")
}
good luck.
function isEmailAddress(str) {
var pattern =/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return pattern.test(str); // returns a boolean
}
Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.
Why?
Syntax validation (according to RFC 822).
IANA TLD validation
Spelling suggestion for the most common TLDs and email domains
Deny temporary email account domains such as mailinator.com
jQuery plugin support
Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..
Example:
test#gnail.com -> Did you mean test#gmail.com?
test#hottmail.con -> Did you mean test#hotmail.com?
How to use it?
The easiest way is to download and include verimail.jquery.js on your page.
After that, hookup Verimail by running the following function on the input-box that needs the validation:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean test#gmail.com?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.
You can also try this expression, I have tested it against many email addresses.
var pattern = /^[A-Za-z0-9._%+-]+#([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$/;
It would be best to use:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,20}$/;
This allows domains such as: whatever.info (4 letters at the end)
Also to test, using
pattern.test("exampleemail#testing.info")
returns true if it works
http://www.w3schools.com/js/js_obj_regexp.asp
I have been using this one....
/^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/
It allows that + before # (xyz+abc#xyz.com)
Little late to the party, but here goes nothing...
function isEmailValid(emailAdress) {
var EMAIL_REGEXP = new RegExp('^[a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$', 'i');
return EMAIL_REGEXP.test(emailAdress)
}
http://jsfiddle.net/yrshaikh/xvd6H/
var emailRegex = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*#[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
if(emailRegex.test('yoursamplemail'))
alert('valid');
else
alert('invalid');
Simple but powerful email validation for check email syntax :
var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+#[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
msg+= "Enter the valid email address!<br />";
}
You should bear in mind that a-z, A-Z, 0-9, ., _ and - are not the only valid characters in the start of an email address.
Gmail, for example, lets you put a "+" sign in the address to "fake" a different email (e.g. someone#gmail.com will also get email sent to someone+else#gmail.com).
micky.o'finnagan#wherever.com would not appreciate your code stopping them entering their address ... apostrophes are perfectly valid in email addresses.
The Closure "check" of a valid email address mentioned above is, as it states itself, quite naïve:
http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/format/emailaddress.js#198
I recommend being very open in your client side code, and then much more heavyweight like sending an email with a link to really check that it's "valid" (as in - syntactically valid for their provider, and also not misspelled).
Something like this:
var pattern = /[^#]+#[-a-z\.]\.[a-z\.]{2,6}/
Bearing in mind that theoretically you can have two # signs in an email address, and I haven't even included characters beyond latin1 in the domain names!
http://www.eurid.eu/en/eu-domain-names/idns-eu
http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
You can add a function to String Object
//Add this wherever you like in your javascript code
String.prototype.isEmail = function() {
return !!this.match(/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
}
var user_email = "test.email#example.com";
if(user_email.isEmail()) {
//Email is valid !
} else {
//Email is invalid !
}

Categories

Resources