Link to home
Start Free TrialLog in
Avatar of BothWorldsJo
BothWorldsJoFlag for United States of America

asked on

Birthday Reg Ex MVC3

Hi!

In an MVC3 C# app I need to watch that a birthdate is entered into a field (mandatory) and is also between 20 and 25 years old.  Is it possible to Reg Ex a date range that changes like that to be sure it's always a certain aged date? Or better to do it in a class function check?
Thanks,
Jo
Avatar of binaryevo
binaryevo
Flag of United States of America image

i would create a validation function and utilize jquery:

var regex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(regex.test($('#brithday').val())){ //do something } 

Open in new window


Note this is not the correct regex expression I just used it as an example.

You can also do regex testing server side...
Avatar of BothWorldsJo

ASKER

Sorry - how does the jquery check that the birthdate is between certain years ago?
It doesnt per say, i was just telling the "how" i would do the validation, forgive me if i wasnt clear.  I thought about this a little bit more and honesty using a regex to do that type of validation is probably not the best way to go about it.  I would use a regex to validate that the dates are valid and then compare them to the range.  
Might you know how the comparison would be written in MVC / razor?
I would do the validation on submit of the form (assuming it is in the form).  Pull it out of the formcollection (or model) in the post method of the controller.  Alternately you could subscribe to the event of the text changing on the actual control and check it in javascript/jquery...but I find it easier to do C#.  :-)

Then just parse the value out as a datetime and compare it to the date range.  If you need examples of this let us know, there are tons of generic validation examples on the web.

some quick psuedo code...in the post action of the controller class
var dateEntered = formcollection["somedatefield"]
if( [dateEntered not in range comparison])
   ModelState.AddModelError("somedatefield", "some error message");
Thanks for the info, could I ask help on the examples?  The ones I found on the net didn't get into the details needed for the date / age comparison but were more if they were greater than some static date, etc.

Here seems to be an example...you may have to translate it or tweak it a bit to fit your needs.

http://developer.force.com/cookbook/recipe/calculating-age-from-date-of-birth
Thanks, and my apologies a bit.  It's not so much how to do the calculation but how to weave it into the MVC 3 view/model so that it's caught and the student is kept on the page since it's not a client side reg ex kind of thing.
ASKER CERTIFIED SOLUTION
Avatar of jmcmunn
jmcmunn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sounds good, thanks for the details.