Validating Email Address.(domain) - regex

I'm Using EmailValidator for Validation:
<mx:EmailValidator id="Email_Validator"
source="{txtEmail}"
property="text" required="false"/>
And My Code is:
var isValidForm:Boolean=true;
var validatorArr:Array = new Array();
validatorArr.push(Email_Validator);
var validatorErrorArray:Array = Validator.validateAll(validatorArr);
isValidForm = validatorErrorArray.length == 0;
if(isValidForm)
{
//.....
}
It is working fine. But I want domain should be "gmail.com" if some other, validation should return false.. How can I achive this?
I think Regular Expressions are usefull.. But I dont Know to use the same in flex?...

If all you are testing for is "gmail.com", you don't need to use regular expressions at all. A simple
if (txtEmail.text.indexOf ("gmail.com") < 0) doStuff();
// index < 0 => address does not contain search string
would be enough.
Nonetheless, ActionScript 3 has the RegExp class to provide regular expression functionality. See this tutorial.

Use a component
checkout this
public class TextInputEmail extends TextInput
{
private var emailValidator:EmailValidator = new EmailValidator();
private var validator:ValidationResultEvent;
public function TextInputEmail()
{
super();
this.emailValidator.source = this;
this.emailValidator.property = "text";
this.addEventListener("enter", this.validate);
}
private function validate(event:Event):void
{
validator = emailValidator.validate();
if (validator.type == ValidationResultEvent.VALID)
{
this.errorString = "";
} else {
this.errorString = validator.message;
}
}
}
error strings are in build in Package.
I hope this helps you better...:-)

Related

How do I create a specimen builder in AutoFixture to always return a string that matches a Regex?

I am trying to use conventions in my unit tests which make use of AutoFixture. I have a Password value object as shown:
public class Password : SemanticType<string>
{
private int _daysPasswordValid;
public Password(string password) : base(IsValid, password)
{
Guard.NotNullOrEmpty(() => password, password);
Guard.IsValid(() => password, password, IsValid, "Invalid Password");
DateCreated = DateTime.Now;
}
static bool IsValid(string candidate)
{
//password cannot contain be whitespace
if (string.IsNullOrWhiteSpace(candidate))
return false;
const string passwordPattern = #"^(?=.*[A-Z].*[A-Z])(?=.*[!##$&=()-*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{20}$";
var match = Regex.Match(candidate, passwordPattern);
return match.Success;
}
public DateTime DateCreated { get; private set; }
public int DaysPasswordValid
{
get { return _daysPasswordValid; }
set
{
const int minimunDays = 0;
const int maximumDays = 90;
if (value <= maximumDays && value > minimunDays)
_daysPasswordValid = value;
else
throw new ArgumentOutOfRangeException(
"Password must be valid more than {0} and no more than {1} days.".Fmt(minimunDays, maximumDays));
}
}
public static implicit operator string(Password password)
{
return password.Value;
}
public static explicit operator Password(string value)
{
return new Password(value);
}
}
I would like to be able to create a fixture based on the Password class and have the fixture created with a valid password, in other words, a password that matches the RegEx pattern in the Password class. I have been looking at the RegularExpressionGenerator available in AutoFixture but haven't quite gotten things to work. Here is the builder have so far:
public class ValidPasswordBuilder : ISpecimenBuilder
{
public ValidPasswordBuilder(string regularExpressionRequest)
{
PasswordRegularExpression = regularExpressionRequest;
}
public string PasswordRegularExpression { get; private set; }
public object Create(object request, ISpecimenContext context)
{
var pi = request as ParameterInfo;
if (pi != null && pi.Name == "password" && pi.ParameterType == typeof(string))
{
var generator = new RegularExpressionGenerator();
var regExRequest = new RegularExpressionRequest(PasswordRegularExpression);
var result = generator.Create(regExRequest, context);
return result.ToString();
}
return new NoSpecimen(request);
}
}
Here is the test:
[Fact]
public void ValidPasswordMatches()
{
var fixture = new Fixture();
fixture.Customizations.Add(new ValidPasswordBuilder(PasswordPattern));
Action a = () => fixture.Create<Password>();
a.ShouldNotThrow<ArgumentException>();
}
I can run the test as setup above, and it passes, but if I debug it, I get an error in the IsValid function in the Password class (through the Guard clause) that says that the password returned from the builder is:
Ploeh.AutoFixture.Kernel.NoSpecimen
I never seem to get a result that matches the RegEx pattern. I feel like I'm close, but need some help getting over the hump.
Thanks!
As it looks like, the pattern you use is not supported:
^(?=.*[A-Z].*[A-Z])(?=.*[!##$&=()-*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{20}$
Try with a different Regular Expression.
Edit: Or try doing this or this, in order to configure AutoFixture to use a different Regular Expression, without changing the Password class.
AutoFixture turns Regular Expressions into Automatons by applying the algorithms of dk.brics.automaton.
You may use a different pattern or use a different engine to reverse the Regular Expression into an Automaton. As an example, you can use the Rex engine.
Though, even with Rex your Regular Expression is not supported, as the following constructs are currently not supported by Rex:
anchors \G, \b, \B, named groups, lookahead, lookbehind, as-few-times-as-possible quantifiers, backreferences, conditional alternation, substitution.
If you want to try Rex with AutoFixture you can use the following generator:
internal class RexRegularExpressionGenerator : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
if (request == null)
return new NoSpecimen();
var regularExpressionRequest = request as RegularExpressionRequest;
if (regularExpressionRequest == null)
return new NoSpecimen();
var pattern = regularExpressionRequest.Pattern;
try
{
var regex = RexEngine
.GenerateMembers(
new RexSettings(pattern) { k = 1 })
.FirstOrDefault();
if (Regex.IsMatch(regex, pattern))
return regex;
}
catch (ArgumentException)
{
return new NoSpecimen(request);
}
return new NoSpecimen(request);
}
}
As far as I can tell, you can download Rex only as a .NET application (.exe) file which you can then reference like any other managed assembly in your project.

Asp.net MVC Test of Create action method with NUnit and Nsubstitute always fails

I have this controller:
[HttpPost]
public ActionResult Create(Company company)
{
// try to save the record
if (ModelState.IsValid)
{
// create the command
var command = new CreateOrUpdateCompanyCommand
{
CompanyId = company.CompanyId,
Code = company.Code,
Name = company.Name
};
// check for errors
IEnumerable<ValidationResult> errors = _commandBus.Validate(command);
ModelState.AddModelErrors(errors);
if (ModelState.IsValid)
{
var result = _commandBus.Submit(command);
if (result.Success)
return RedirectToAction("Index");
}
}
// if fail
return View("Create", company);
}
I have this test for NUnit:
[Test]
public void Create()
{
const string expectedRouteName = "Index";
// Mock the arguments
var mockRepository = Substitute.For<ICompanyRepository>();
var mockProcessor = Substitute.For<ICommandBus>();
// Arrange
var controller = new CompanyController(mockProcessor, mockRepository);
// Act
var company = new Company
{
Code = "XXXXXXX",
CompanyId = 1,
Name = "Sample company"
};
var result = controller.Create(company) as RedirectToRouteResult;
// Assert
Assert.IsNotNull(result, "Should return a ViewResult");
Assert.AreEqual(expectedRouteName, result.RouteValues["action"],
"View name should have been '{0}'", expectedRouteName);
}
This is the Model:
public class Company
{
[Key]
public int CompanyId { get; set; }
[Required(ErrorMessage = "* (xxxx)")]
[MaxLength(7)]
[RegularExpression("^([A-Z0-9]{7})$", ErrorMessage = "xxx")]
[Display(Name = "Code")]
public string Code { get; set; }
[Required(ErrorMessage = "*")]
[MaxLength(40)]
[Display(Name = "Name")]
public string Name { get; set; }
}
When I Run the test, this function always return false: var result = _commandBus.Submit(command); and the test fails.
I don't know how to test it? Should I mock the _commandBus and set it to return true? I tried in this way but unsuccessfully:
var mockCommand = Substitute.For<ICommand>();
mockProcessor.Submit(mockCommand).Success.Returns(true);
To create this project I have got inspiration from this http://efmvc.codeplex.com/
Any advise to me? Thanks.
The command you pass to mockProcessor.Submit(mockCommand).Success.Returns(true) needs to be the same one that the code-under-test passes. As the method news up its own command this will never be the case.
Easiest fix is to match any command when you set up your substitute:
var result = CreateSuccessfulResult(); // <-- fill this in as appropriate
mockProcessor.Submit(null).ReturnsForAnyArgs(result);
Setting the Success field on result inline as per your original test should work too I think, but I find it a bit clearer to specify the result required.
You can improve this a bit by matching the expected command type:
mockProcessor.Submit(Arg.Any<CreateOrUpdateCompanyCommand>()).Returns(result);
You can also inspect the command passed if you'd like to test that:
mockProcessor
.Submit(Arg.Is<CreateOrUpdateCompanyCommand>(x => x.CompanyId = ...))
.Returns(result);
A similar approach can be used to check the Validate call.
There's a bit more info in the NSubstitute docs.

How do I create a regex to remove underscore

I am using MVC 3 with Razor. I can't figure out how to code a string extension regex to take this:
This_is_some_text
to display:
This is some text
I set up some enums for a drop down list, so they appear thusly (obviously I can't create an enum with a space):
public enum MyProperty
{
This_is_some_text,
This_is_some_other_text
}
I just cannot figure out the regex is to do what I want if I am doing this:
public static string EnumToDisplay(this string str)
{
return Regex.Replace(str, "[What is the regex I should use?]");
}
As a bonus for me I would also like to add a period "." to the end of the enum. The reason for this is that I have OCD and my enums are taking the form of short sentences. :)
Thanks!
Why not use String.Replace() for this? RegEx seems a bit overkill.
public static string EnumToDisplay(this string str)
{
return str.Replace('_', ' ') + ".";
}
Why do you want to use regular expressions? A very wise man once said, I quote:
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems.
How about using the [Display] attribute which is kinda designed exactly for this purpose:
public enum MyProperty
{
[Display(Name = "This is some super text")]
This_is_some_text,
[Display(Name = "And this is some other text")]
This_is_some_other_text
}
and then writing a custom Html helper:
public static class HtmlExtensions
{
public static IHtmlString DisplayForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
if (!typeof(TProperty).IsEnum)
{
throw new ArgumentException("sorry this helper is inteded to be used with enum types");
}
var model = htmlHelper.ViewData.Model;
if (htmlHelper.ViewData.Model == null)
{
return MvcHtmlString.Empty;
}
var field = typeof(TProperty).GetField(expression.Compile()(htmlHelper.ViewData.Model).ToString());
if (field == null)
{
return new HtmlString(htmlHelper.Encode(htmlHelper.ViewData.Model.ToString()));
}
var display = field.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault() as DisplayAttribute;
if (display == null)
{
return new HtmlString(htmlHelper.Encode(htmlHelper.ViewData.Model.ToString()));
}
return new HtmlString(htmlHelper.Encode(display.Name));
}
}
So now assuming you have a view model:
public class MyViewModel
{
public MyProperty Foo { get; set; }
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Foo = MyProperty.This_is_some_other_text
};
return View(model);
}
}
you could use the custom helper we just wrote in the view to display a user friendly text that we might have associated to an ugly enum. Hey, now you could even have this working with globalization and multiple languages using resources:
#model MyViewModel
#Html.DisplayForEnum(x => x.Foo)
I do not know about asp.net - but there should be a really simple method that replaces one character with another char. Like:
String.replace( myString, '_',' ' );
You can use the replacement pattern which is also called substitution.
You can find graet info here:
http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx
Good luck

RegularExpressionAttribute - How to make it not case sensitive for client side validation?

I have a string that I use for client side validation:
private const String regex = #"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";
I use this string in my [RegularExpression(regex, ErrorMessage = "invalid")] attribute.
I know that the /i flag for a Javascript regex is used to make it case insensitive, but just tacking it on to the end of my regex (i.e. #"^....$/i" isn't working - the regex validation fails completely, regardless of what is entered (valid or not).
What am I missing?
I created this attribute which allows you to specify RegexOptions. EDIT: It also integrates with unobtrusive validation. The client will only obey RegexOptions.Multiline and RegexOptions.IgnoreCase since that is what JavaScript supports.
[RegularExpressionWithOptions(#".+#example\.com", RegexOptions = RegexOptions.IgnoreCase)]
C#
public class RegularExpressionWithOptionsAttribute : RegularExpressionAttribute, IClientValidatable
{
public RegularExpressionWithOptionsAttribute(string pattern) : base(pattern) { }
public RegexOptions RegexOptions { get; set; }
public override bool IsValid(object value)
{
if (string.IsNullOrEmpty(value as string))
return true;
return Regex.IsMatch(value as string, "^" + Pattern + "$", RegexOptions);
}
public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "regexwithoptions"
};
rule.ValidationParameters["pattern"] = Pattern;
string flags = "";
if ((RegexOptions & RegexOptions.Multiline) == RegexOptions.Multiline)
flags += "m";
if ((RegexOptions & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
flags += "i";
rule.ValidationParameters["flags"] = flags;
yield return rule;
}
}
JavaScript
(function ($) {
$.validator.unobtrusive.adapters.add("regexwithoptions", ["pattern", "flags"], function (options) {
options.messages['regexwithoptions'] = options.message;
options.rules['regexwithoptions'] = options.params;
});
$.validator.addMethod("regexwithoptions", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
var reg = new RegExp(params.pattern, params.flags);
match = reg.exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
})(jQuery);
This article by Anthony Stevens helped me get this working: ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators
In C# you can inline some regex options. To specify the option to ignore case you would add (?i) to the beginning of your pattern. However, I am not sure how this would be treated by the RegularExpressionAttribute and if it handles translation for client-side. From my experience with ASP.NET's RegularExpressionValidator I doubt it; the regex should be vanilla enough to work for both engines.
In any case if it was valid it would look like this:
#"^(?i)(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$"
private const String regex = #"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([a-zA-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";

Validating email addresses using jQuery and regex

I'm not too sure how to do this. I need to validate email addresses using regex with something like this:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)
Then I need to run this in a jQuery function like this:
$j("#fld_emailaddress").live('change',function() {
var emailaddress = $j("#fld_emailaddress").val();
// validation here?
if(emailaddress){}
// end validation
$j.ajax({
type: "POST",
url: "../ff-admin/ff-register/ff-user-check.php",
data: "fld_emailaddress="+ emailaddress,
success: function(msg)
{
if(msg == 'OK') {
$j("#fld_username").attr('disabled',false);
$j("#fld_password").attr('disabled',false);
$j("#cmd_register_submit").attr('disabled',false);
$j("#fld_emailaddress").removeClass('object_error'); // if necessary
$j("#fld_emailaddress").addClass("object_ok");
$j('#email_ac').html(' <img src="img/cool.png" align="absmiddle"> <font color="Green"> Your email <strong>'+ emailaddress+'</strong> is OK.</font> ');
} else {
$j("#fld_username").attr('disabled',true);
$j("#fld_password").attr('disabled',true);
$j("#cmd_register_submit").attr('disabled',true);
$j("#fld_emailaddress").removeClass('object_ok'); // if necessary
$j("#fld_emailaddress").addClass("object_error");
$j('#email_ac').html(msg);
}
}
});
});
Where does the validation go and what is the expression?
UPDATES
http://so.lucafilosofi.com/jquery-validate-e-mail-address-regex/
using new regex
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
}
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
NOTE: keep in mind that no 100% regex email check exists!
This is my solution:
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
// alert( pattern.test(emailAddress) );
return pattern.test(emailAddress);
};
Found that RegExp over here: http://mdskinner.com/code/email-regex-and-validation-jquery
$(document).ready(function() {
$('#emailid').focusout(function(){
$('#emailid').filter(function(){
var email = $('#emailid').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ( !emailReg.test( email ) ) {
alert('Please enter valid email');
} else {
alert('Thank you for your valid email');
}
});
});
});
Lolz this is much better
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/);
return pattern.test(emailAddress);
};
I would recommend that you use the jQuery plugin for Verimail.js.
Why?
IANA TLD validation
Syntax validation (according to RFC 822)
Spelling suggestion for the most common TLDs and email domains
Deny temporary email account domains such as mailinator.com
How?
Include verimail.jquery.js on your site and use the function:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
Javascript:
var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);
The regex is not allowed for:
abc#gmail..com
abc#gmail.com..
Allowed for:
abc.efg#gmail.com
abc#gmail.com.my
Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/
We can also use regular expression (/^([\w.-]+)#([\w-]+)((.(\w){2,3})+)$/i) to validate email address format is correct or not.
var emailRegex = new RegExp(/^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$/i);
var valid = emailRegex.test(emailAddress);
if (!valid) {
alert("Invalid e-mail address");
return false;
} else
return true;
Try this
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
return pattern.test(emailAddress);
};
you can use this function
var validateEmail = function (email) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
if (pattern.test(email)) {
return true;
}
else {
return false;
}
};
Native method:
$("#myform").validate({
// options...
});
$.validator.methods.email = function( value, element ) {
return this.optional( element ) || /[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}/.test( value );
}
Source: https://jqueryvalidation.org/jQuery.validator.methods/