Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Form Validation, Only Allow .EDU Email Addresses

I am using the jquery validate function and plugin located here. http://docs.jquery.com/Plugins/Validation

I am going thrue the js file and i have found the email validation block that makes sure it is a valid email, the thing is, i want to only allow .edu emails. I have no idea where to start.

like image 202
Connor Finn McKelvey Avatar asked Dec 12 '22 06:12

Connor Finn McKelvey


2 Answers

You can extend it and add your own rule.

jQuery.validator.addMethod("edu", function(value, element) {
  // Make it work optionally OR
  //  Check the last 4 characters and ensure they match .edu
  return (this.optional(element) || value.slice(-4) == ".edu"); 
}, "You must use a .edu email address");

$("#myform").validate({
  rules: {
    field: {
      required: true,
      email: true,
      edu: true
    }
  }
});

Here is a jsfiddle showing how it all works together and how the errors cascade. Just press the button.

like image 183
Brombomb Avatar answered Jan 31 '23 07:01

Brombomb


You don't need custom extension. You can use accept() method: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension

// input field
<input type="text" id="eduEmail2" name="eduEmail2" value="[email protected]"/>

// validation rule
eduEmail2: {
    required: true,
    email: true,
    accept: 'edu'
}

Full example: http://jsfiddle.net/M5TmU/2/ (based on Brombomb's jsfiddle)

UPDATE

After xecute's comment - you may use custom regex pattern. In additional-methods.js you have "pattern" method (last one in a file):

eduEmail3: {
    required: true,
    email: true,
    pattern: /(\.edu\.\w\w)$/
}

Full example: http://jsfiddle.net/M5TmU/3/

Of course it's not perfect, but still - you don't need write custom method :)

ADDITIONAL EDIT: country domain names have two letters, so \w\w\w? is too much - \w\w should do. I left \w\w\w? in fiddle

like image 32
BartekR Avatar answered Jan 31 '23 06:01

BartekR