JavaScript/JQuery Regular Expressions: The Regex Object: Form Validation: Angular Form Validation

--

In web programming, regular expressions are very useful. Very often, you have to validate forms to satisfy different validation rules. Regular expressions become very handy in such cases. Especially to validate emails, domain names, and fields only allowing alphanumeric input or similar regular expressions are always used.

Another area where understanding of Regular Expressions is crucial is Compiler Design i.e. programming language design and implementation. In a compiler design course, you must be taught Regular Expressions. For example, the document/book http://www.cc.uah.es/ie/docencia/ProcesadoresDeLenguaje/libros/basics_lulu.pdf on compiler design has a chapter on lexical analysis and regular expressions. Lexical analysis is the reading of your program and breaking your programs into tokens as part of compiling.

Anyway, back to JavaScript Regular Expressions:

JavaScript has an Object called RegExp to work with Regular Expressions. The syntax is RegExp (pattern, modifier). Where pattern indicates the pattern you are searching for, and the modifier tells how to go about the search/(pattern matching) such as will it be in global scope or will it be case sensitive or not.

Methods of the RegExp object includes test(), exec(), and toString(). test() returns true or false based on success or failure of the search. exec() will return the matched text. toString() when applied to a regular expression object will return the pattern in string.

Recent AngularJS also makes use of regular expressions for form validations such as:

<input type="text" ng-pattern="[a-zA-Z]" />Details on Form Validation for Angular is at the end of this article.
Also, be aware of the new novalidate directive for form validation supported by IE 10+, Firefox, Opera, and Chrome.

RegExp object properties:

constructor : return the function that created the RegExp object

global : will return true or false based on global is set or not

ignorecase : will return true or false based on case-insensitivity is set or not

lastindex : will return the index to do the next search. when you are using test() method, it will match one at a time.. so if you want you can find the last index

multiple : if the m modifier set or not

source : source text of the pattern

Now, little code

var searchPattern =new RegExp(pattern,modifiers);

or:

var patt=/pattern/modifiers;

Example:

var patt1=/justetc/i; where i indicates that it is a case insensitive search.

var str=”Hello world”;
var patt1=/wor/g;

Test Method Example

var searchPattern = new RegExp(“wor”);
searchPattern.test(“hello world”));

Will return True

exec() method example

var searchPattern = new RegExp(“wor”);
searchPattern.exec(“hello world”));

Will return wor

toString() example

var patt = new RegExp(“Hello World”,”g”);
var res = patt.toString();

Will return: /Hello World/g

Property related examples

var patt1 = /xyz/g;
patt1.source will return xyz

— -

Modifier details:

i — case insensitive

g — find all matches

m — multiple match

Some rules with brackets in the pattern

[xyz] : any character in braces

[^xyz] : any character not in braces

[0–9]: any digit between braces

[⁰-5] : any digit not in between brackets

(x|y) : any character in between braces

Meta Characters used in Regular Expressions : Characters that have special meaning

\d : find digit

\D : non digit

\w : word character

\W : non word character

\s : space character

\S : non-space character

\b : find at the beginning

\B : not at the beginning

: find null character

\n : find newline character

\f : form feed character

\r: carriage return character

\t : find a tab character

\xxx: find the character who has an octal code xxx

\xdd : find the character who has an hexa decimal code dd

\uxxxx : find the character with the unicode code

Regular Expression Quantifiers:

n+ : at least one n

n* : 0 or more n

n? : 0 or 1 occurrence of n

n{X} : X number of n’s

n{X, Y} : X to Y number of n’s

n{X,} : at least X number of n’s

n$ : string that ends with n

^n : starts with n

?=ntt : strings followed by the string ntt

?!n : strings that are not followed by the string n

Related Resource:

validate.js is a JS/Jquery based package for form validation.

http://rickharrison.github.io/validate.js/

You can also use JQuery Validation Plugin for form validations

http://jqueryvalidation.org/

How to use validate.js package:

Include the JavaScript file in your source

<script type="text/javascript" src="validate.min.js"></script>

Create the validation object with your desired rules. This needs to be in a <script> tag located just before your closing </body> tag. The reason for this being that the DOM needs to have your form loaded before you can attach your rules.

var validator = new FormValidator('example_form', [{
name: 'req',
display: 'required',
rules: 'required'
}, {
name: 'alphanumeric',
rules: 'alpha_numeric'
}, {
name: 'password',
rules: 'required'
}, {
name: 'password_confirm',
display: 'password confirmation',
rules: 'required|matches[password]'
}, {
name: 'email',
rules: 'valid_email'
}, {
name: 'minlength',
display: 'min length',
rules: 'min_length[8]'
}], function(errors, event) {
if (errors.length > 0) {
// Show the errors
}
});

FormValidator

new FormValidator(formName, fields, callback)

— — — — — — — -

A JQuery validation plugin usage example can be found at:

http://jquery.bassistance.de/validate/demo/

Taken from the web-site [opensource. right?]

<script src="../lib/jquery.js"></script>
<script src="../jquery.validate.js"></script>
<script>
$.validator.setDefaults({
submitHandler: function() { alert("submitted!"); }
});
$().ready(function() {
// validate the comment form when it is submitted
$("#commentForm").validate();
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
// propose username by combining first- and last name
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if(firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
//code to hide topic selection, disable for demo
var newsletter = $("#newsletter");
// newsletter topics are optional, hide at first
var inital = newsletter.is(":checked");
var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
var topicInputs = topics.find("input").attr("disabled", !inital);
// show when newsletter is checked
newsletter.click(function() {
topics[this.checked ? "removeClass" : "addClass"]("gray");
topicInputs.attr("disabled", !this.checked);
});
});
</script>
AngularJS form Validation
http://docs.angularjs.org/guide/forms
Must Read:
http://www.ng-newsletter.com/posts/validations.html
Angular provides basic implementation for most common html5 input types: (text, number, url, email, radio, checkbox), as well as some directives for validation (required, pattern, minlength, maxlength, min, max). Other Resources: Regular Expressions in Java http://docs.oracle.com/javase/tutorial/essential/regex/ Regular Expressions in .Net http://msdn.microsoft.com/en-us/library/hs600312%28v=vs.110%29.aspx

--

--

Justetc Social Services (non-profit)

All proceeds from Medium will go to Justetc Social Services ( non-profit). Justetc Social Services provides services in the Training and Education Areas.