Unable to validate only space in email validation by using [EmailAddress] annotation - validation

I am using [EmailAddress] data annotation to validate email address. I've noticed that if I add space than it is not working. It works fine if I use period, hyphen, underscore but space.
Model:
[DisplayName(#"Custom Email Confirmation Address")]
[EmailAddress(ErrorMessage = #"Invalid Email Address")]
public string CustomEmailConfirmationAddress { get; set; }
Custom Control:
<div>
<%=Html.RequiredLabelFor(m => m.CustomEmailConfirmationAddress) %>
<%=Html.TextBoxFor(m => m.CustomEmailConfirmationAddress, new { maxlength = 100 })%>
<%=Html.ValidationMessageFor(m => m.CustomEmailConfirmationAddress)%>
</div>
On Browser: For space class="textboxhelp-focus valid"
<div>
<label class="required" for="CustomEmailConfirmationAddress">Custom Email Confirmation Address</label>
<input id="CustomEmailConfirmationAddress" class="textboxhelp-focus valid" type="text" value="" name="CustomEmailConfirmationAddress" maxlength="100" data-val-email="Invalid Email Address" data-val="true" help="noreply#example.com" style="width: 300px;">
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="CustomEmailConfirmationAddress"></span>
</div>
For Underscore: class="textboxhelp-focus input-validation-error"
<div>
<label class="required" for="CustomEmailConfirmationAddress">Custom Email Confirmation Address</label>
<input id="CustomEmailConfirmationAddress" class="textboxhelp-focus input-validation-error" type="text" value="" name="CustomEmailConfirmationAddress" maxlength="100" data-val-email="Invalid Email Address" data-val="true" help="noreply#example.com" style="width: 300px;">
<span class="field-validation-error" data-valmsg-replace="true" data-valmsg-for="CustomEmailConfirmationAddress">
</div>
Am I missing something here?

Related

Form is not saved because it has errors, but errors are not displayed

I have a SignUp form for user, also I have a validation for fields, I'll provide all of that. So, when user insert for example on field username > s but that field need to have more then 3 characters, program should show error and not save that data into table. What's happening? Application process the error, I mean form is not submitted when I made a error on purpose, but error is not showing on HTML, not on stack trace. Page is just returned but error message are not showing, good thing is just that form is not saved if there is error so that work, problem is just message not appearing.
I have a SignUp form, and for example I have this validation on username and firstName:
#NotEmpty
#Size(min = 3, max = 20, message = "Username not valid")
private String username;
#NotEmpty(message = "Please, insert a first name")
private String firstName;
This is how I display form, its login and register on same page, that is why I have two model attributes:
#GetMapping("/loginAndRegisterForm")
public String showLoginForm(Model model) {
// create model object to store form data
LoginRequest loginRequest = new LoginRequest();
SignupRequest signupRequest = new SignupRequest();
model.addAttribute("login", loginRequest);
model.addAttribute("user", signupRequest);
return "login_and_registration";
}
This is SignUp controller, with result.hasErrors() inside it:
#PostMapping("/signup")
#Transactional
public String signup(#ModelAttribute("signup") #Valid SignupRequest signupRequest, BindingResult result, Model model) throws Exception {
boolean thereAreErrors = result.hasErrors();
if (thereAreErrors) {
LoginRequest loginRequest = new LoginRequest();
model.addAttribute("user", signupRequest);
model.addAttribute("signup", signupRequest);
model.addAttribute("login", loginRequest);
return "login_and_registration";
}
User user = new User(signupRequest.getUsername(), signupRequest.getFirstName(), signupRequest.getLastName(), signupRequest.getEmail(), encoder.encode(signupRequest.getPassword()));
model.addAttribute("signup", signupRequest);
userRepository.save(user);
return "redirect:/api/auth/loginAndRegisterForm";
}
And this is Thymeleaf:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Security Tutorial</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/loginAndRegistration.css}"/>
</head>
<body>
<div class="main">
<input type="checkbox" id="chk" aria-hidden="true">
<div class="signup">
<form
method="post"
role="form"
th:action="#{/api/auth/signup}"
th:object="${user}">
<label for="chk" aria-hidden="true">Sign up</label>
<input
class="form-control"
id="usernameSignUp"
name="username"
placeholder="Enter username"
th:field="*{username}"
type="text"/>
<p th:errors="*{username}" class="text-danger"
th:if="${#fields.hasErrors('username')}"></p>
<input
class="form-control"
id="firstName"
name="firstName"
placeholder="Enter first name"
th:field="*{firstName}"
type="text"/>
<p th:errors="*{firstName}" class="text-danger"
th:if="${#fields.hasErrors('firstName')}"></p>
<input
class="form-control"
id="lastName"
name="lastName"
placeholder="Enter lastName"
th:field="*{lastName}"
type="text"/>
<p th:errors="*{firstName}" class="text-danger"
th:if="${#fields.hasErrors('firstName')}"></p>
<input
class="form-control"
id="email"
name="email"
placeholder="Enter email"
th:field="*{email}"
type="email"/>
<p th:errors="*{email}" class="text-danger"
th:if="${#fields.hasErrors('email')}"></p>
<input
class="form-control"
id="passwordSignUp"
name="password"
placeholder="Enter password"
th:field="*{password}"
type="password"/>
<p th:errors="*{password}" class="text-danger"
th:if="${#fields.hasErrors('password')}"></p>
<button>Sign up</button>
</form>
</div>
<div class="login">
<form
method="post"
role="form"
th:action="#{/api/auth/login}"
th:object="${login}">
<label for="chk" aria-hidden="true">Login</label>
<input
class="form-control"
id="usernameLogin"
name="username"
placeholder="Enter username"
th:field="*{username}"
type="text"/>
<p th:errors="*{username}" class="text-danger"
th:if="${#fields.hasErrors('username')}"></p>
<input
class="form-control"
id="passwordLogin"
name="password"
placeholder="Enter password"
th:field="*{password}"
type="password"/>
<p th:errors="*{password}" class="text-danger"
th:if="${#fields.hasErrors('password')}"></p>
<button>Login</button>
</form>
</div>
</div>
</body>
</html>

Adding Dropdown to Register.cshtml in Identity

I am using Microsoft Identity in my Asp.NET MVC Core 7.0 application with a customized IdentityUser:
public class SparkleWebAppUser : IdentityUser
{
[Required(ErrorMessage = "Must provide a user name")]
[StringLength(15, ErrorMessage = "User name cannot be longer than 15 letters")]
[Display(Name = "User Name")]
public override string UserName { get; set; } = string.Empty;
[Required(ErrorMessage = "Must provide first name")]
[StringLength(20, ErrorMessage = "First name cannot be longetr than 20 letters")]
public string FirstName { get; set; } = string.Empty;
[Required(ErrorMessage = "Must provide last name")]
[StringLength(20, ErrorMessage = "First name cannot be longer than 20 letters")]
public string LastName { get; set; } = string.Empty;
[Required(ErrorMessage = "Must provide a parent id to continue. Please contact your company/organisation to get parents id.")]
[Display(Name = "Your Organization's ID")]
public int OrgId { get; set; }
[Required(ErrorMessage = "Must mention type of application user")]
//[ForeignKey("UserType")]
public AppUserType AppUserType { get; set; }
[NotMapped]
public IEnumerable<AppUserType> SelectedAppUserType { get; set; }
public virtual WorkLocation? OfficeName { get; set; }
[Required(ErrorMessage = "Must provide Id Number provided to you by your organization")]
[DataType(DataType.Text)]
[Display(Name = "Your personal ID in the organization")]
public string IdNumber { get; set; } = string.Empty;
[Display(Name = "Profile Picture")]
public byte[]? ProfilePic { get; set; }
[Display(Name = "Full Name")]
[NotMapped]
public string FullName { get { return (FirstName + " " + LastName); } }
}
below is the model of AppUserType:
public class AppUserType
{
[Key]
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required]
[StringLength(15, ErrorMessage = "Name cannot be longer than 15 letters")]
[Display(Name = "User Type Name")]
public string Name { get; set; } = String.Empty;
[Display(Name = "App Users")]
public ICollection<SparkleWebAppUser>? lIMISAppUsers { get; set; }
}
The Register in Identity is given below:
#page
#using iStar.Sparkle.WebDev.Areas.Identity.Models;
#model RegisterModel
#{
ViewData["Title"] = "New User Sign Up";
//Layout = "~/Areas/Identity/Views/Shared/_IdentityLayout.cshtml";
}
<h1>#ViewData["Title"]</h1>
<div class="row">
<div class="col-md-4">
<form id="registerForm" asp-route-returnUrl="#Model.ReturnUrl" method="post">
<h2>Create a new account.</h2>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div>
<div class="form-floating mb-3">
<input asp-for="Input.UserName" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />
<label asp-for="Input.UserName">User Name</label>
<span asp-validation-for="Input.UserName" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.FirstName" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />
<label asp-for="Input.FirstName">First Name</label>
<span asp-validation-for="Input.FirstName" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.LastName" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />
<label asp-for="Input.LastName">Last Name</label>
<span asp-validation-for="Input.LastName" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.OrgId" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />
<label asp-for="Input.OrgId">Company ID</label>
<span asp-validation-for="Input.OrgId" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.OfficeName" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />
<label asp-for="Input.OfficeName">Company's Office Name</label>
<span asp-validation-for="Input.OfficeName" class="text-danger"></span>
</div>
#* <div class="form-floating mb-3">
<input asp-for="Input.AppUserType" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />
<label asp-for="Input.AppUserType">Access Type</label>
<span asp-validation-for="Input.AppUserType" class="text-danger"></span>
</div>*#
<div class="form-group mb-3">
#*<select asp-for="Input.AppUserType" asp-items="#(new SelectList(AppUserType, "Id", "Name"))" value="Id">Access Type</select>*#
#*<input asp-for="Input.AppUserType" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />*#
<label asp-for="Input.AppUserType">Access Type</label>
<span asp-validation-for="Input.AppUserType" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.Email" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />
<label asp-for="Input.Email">Email</label>
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.Password" class="form-control" autocomplete="new-password" aria-required="true" placeholder="password" />
<label asp-for="Input.Password">Password</label>
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.ConfirmPassword" class="form-control" autocomplete="new-password" aria-required="true" placeholder="password" />
<label asp-for="Input.ConfirmPassword">Confirm Password</label>
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<button id="registerSubmit" type="submit" class="w-100 btn btn-lg btn-primary">Register</button>
</form>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
<h3>Use another service to register.</h3>
<hr />
#{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
There are no external authentication services configured. See this <a href="https://go.microsoft.com/fwlink/?LinkID=532715">article
about setting up this ASP.NET application to support logging in via external services</a>.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="#Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
#foreach (var provider in Model.ExternalLogins!)
{
<button type="submit" class="btn btn-primary" name="provider" value="#provider.Name" title="Log in using your #provider.DisplayName account">#provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
I want to use a drop down SelectItemList for AppUserType in the Register page. I have tried several ways but none is working. The last one mentioned here
<div class="form-group mb-3">
<select asp-for="Input.AppUserType" asp-items="#(new SelectList(AppUserType, "Id", "Name"))" value="Id">Access Type</select>
#*<input asp-for="Input.AppUserType" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />*#
<label asp-for="Input.AppUserType">Access Type</label>
<span asp-validation-for="Input.AppUserType" class="text-danger"></span>
</div>
looks quite sensible but I don't know how can I fill the drop down from table 'AppUserTypes' in this dropdown.
Is your dropdown's value from a database table?
You can try to create a property into the RegisterModel:
[BindProperty]
public SelectList DropDown { get; set; }
public async Task OnGetAsync(string returnUrl = null)
{
DropDown = new SelectList(_context.AppUserType.ToList(),"Id","Name");
//...
}
And in Register.cshtml:
<div class="form-group mb-3">
<select asp-for="Input.AppUserType" aria-required="true" asp-items="#Model.DropDown" value="Id">Access Type</select>
#*<input asp-for="Input.AppUserType" class="form-control" autocomplete="on" aria-required="true" placeholder="name#example.com" />*#
<label asp-for="Input.AppUserType">Access Type</label>
<span asp-validation-for="Input.AppUserType" class="text-danger"></span>
</div>

Display Friendly Error Message When using Decorators in Models

New to ASP.NET Core.
I have a view:
<form asp-action="LogIn">
<div class="form-horizontal">
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EmailAddress" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="EmailAddress" class="form-control" style="min-width:350px" />
<span asp-validation-for="EmailAddress" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Password" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Password" class="form-control" style="min-width:350px" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enter" class="btn btn-default" />
</div>
</div>
</div>
</form>
I have this Model for it:
public class Subscription
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long SubscriptionId { get; set; }
[Display(Name = "Email Address")]
[Required]
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*")]
public string EmailAddress { get; set; }
[NotMapped]
public string Password { get; set; }
}
So, when a User types in an email address that is not validated by the regular expression I get the error message:
How do i over-ride this 'default' error message to say (for example):
Email Address is Invalid
?
You need to add ErrorMessage property to the RegularExpression attribute like this-
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Your friendly message goes here")]

Jquery Validate EqualTo Issue [duplicate]

This question already has an answer here:
Using jquery.validation equalTo( other ) to ensure "Sunday" is the inputted value
(1 answer)
Closed 8 years ago.
I have the following code
$("#emailForm").validate({
rules: {
"UserPasswordReset.EmailAddress": {
maxlength: 256,
email: true,
},
"UserPasswordReset.ConfirmEmailAddress": {
maxlength: 256,
email: true,
equalTo: "#UserPasswordReset.EmailAddress"
}
}
});
When I fill in the below form and press submit I says on the confirm box please enter the same value so I check, double check and for the love of god I check again, but still I get please enter the same value even though both fields are identical.
<div id="home" class="tab-pane active" role="tabpanel">
<div class="form-group">
<label class="col-sm-1 control-label no-padding-right" for="form-field-1-1"> Email</label>
<div class="col-sm-9">
<input id="emailaddress" class="col-xs-10 col-sm-5" type="text" value="" name="UserPasswordReset.EmailAddress" data-val-required="The EmailAddress field is required." data-val="true" autocomplete="off" placeholder="Please enter your email address">
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label no-padding-right" for="form-field-1-1"> Confirm </label>
<div class="col-sm-9">
<input id="confirm_email" class="col-xs-10 col-sm-5" type="text" value="" name="UserPasswordReset.ConfirmEmailAddress" autocomplete="off" placeholder="Please confirm your email address">
</div>
</div>
<button id="btnSaveEmail" class="btn btn-info pull-right" type="Submit" value="true" name="SaveEmailAddress"> Update Email </button>
</div>
What am I doing wrong here?
You ConfirmEmailAddress rule has
equalTo: "#UserPasswordReset.EmailAddress"
You don't have a control with id="UserPasswordReset.EmailAddress" (only one with id="emailaddress"). Change it to
equalTo: "#emailaddress"

MVC 3 Format Validation Messages

I am working with a form layout that has 4 input fields per row so I need to find a different way to display the validation messages. I was thinking I could display any messages above the form but would like to add a border and a background color.
I am using unobtrusive JS for validation.
Is there a way to detect if there are validation errors from the view?
Example
#using (Ajax.BeginForm("ProcessContactInfo", ajaxOpts))
{
#Html.ValidationSummary(true)
if (!ViewData.ModelState.IsValid)//does nothing because using unobtrusiveJS validation
{
<div id="ValidationResultsArea" style="padding:20px; border: 1px solid #000000; background-color: #ffffcc; display: none" >
#Html.ValidationMessageFor(model => model.Contact.FirstName)<br />
#Html.ValidationMessageFor(model => model.Contact.LastName)<br />
#Html.ValidationMessageFor(model => model.Contact.Email)<br />
#Html.ValidationMessageFor(model => model.Contact.Message)<br />
</div>
}
<p><span class="required">* All fields are required.</span></p>
}
Looks like you are looking for something similar to this....
If that is what you are looking for, then you can easily achieve it if you are using MVC3 and jquery validation. jQuery validation uses custom data attributes, css and unobtrusive javascript to perform user input validation, so when validation fails for a specific input field, jQuery "injects" data attributes and css classes, then you can take advantage of this by using css to define how you want to the fields to look like. Here's the HTML belonging to the screenshot above...
<div class="editor-label">
<label for="UserName" style="display: none;">User name</label>
</div>
<div class="editor-field">
<span class="field-validation-error" data-valmsg-for="UserName" data-valmsg-replace="true">The User name field is required.</span>
<input class="input-validation-error" data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" placeholder="Username" type="text" value="">
</div>
<div class="editor-label">
<label for="Password" style="display: none;">Password</label>
</div>
<div class="editor-field">
<span class="field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true">The Password field is required.</span>
<input class="input-validation-error" data-val="true" data-val-required="The Password field is required." id="Password" name="Password" placeholder="Password" type="password">
</div>
<div class="editor-label">
<input data-val="true" data-val-required="The Remember me? field is required." id="RememberMe" name="RememberMe" type="checkbox" value="true"><input name="RememberMe" type="hidden" value="false"> Remember Me
</div>
<p>
<input type="submit" value="Log On">
</p>
You can see that jQuery Validation framework added a class (input-validation-error) to the Username input field. You can specify override this css class in your project.

Resources