I'm using a rails form with client side validations. How can I customize the error message, which current says:
"Value must be equal to or greater than ... "
Here is the form field:
<%= f.number_field :age, placeholder:"Age", class:"form-control", required: true, max:90, min:17, message: 'foo' %>
HTML5 API has a way to set custom error validation message. Look below the example:
Example:
<form>
<label for="mail">I would like you to provide me an e-mail</label>
<input type="email" id="mail" name="mail">
<button>Submit</button>
</form>
And then adding a JS:
var email = document.getElementById("mail");
email.addEventListener("keyup", function (event) {
if (email.validity.typeMismatch) {
email.setCustomValidity("I expect an e-mail, darling!");
} else {
email.setCustomValidity("");
}
});
Documentation of setCustomValidity().
Related
I am working on reactive form like In my reactive form having 3 fields but in which 2 are mandatory and one is non mandatory but it has validation like if user enter a string in respective field it has minimum character limit example 10 character. but i faced issue when user has enter string it is showing error but submit button is not going to disable.
return FormBuilder.group({
'surveyDueDate': ['', Validators.required],
'rfsDueDate': [null, Validators.required],
'comment': [null]
});
<form (ngSubmit)="submit(form)" #form="ngForm">
<div>
Survey date:
<input name="surveyDueDate" [(ngModel)]="surveyDueDate">
</div>
<div>
Due Date :
<input name="rfsDueDate" [(ngModel)]="rfsDueDate">
</div>
<div>
Gift shipping address:
<input name="comment">
</div>
<button type="submit" [disabled]="form.invalid">Register now!</button>
</form>
thanks in advance.
In your component listen for the particular field changes. For example,
this.form.controls["comment"].valueChanges().subscribe((commentValue)=>{
if(commentValue && commentValue.length>10 && this.form.invalid===false){
this.form.controls["comment"].setErrors({invalid:true});
} else {
this.form.controls["comment"].setErrors(null);
}
});
my login page( build with simple form) add by default html attributes for browser validation on email input that chrome doesn't recognize and show "Please match the requested format."
Maybe is Chrome bug(on firefox works), so have tried to disable browser validation with simple form config
SimpleForm.html5 and SimpleForm.browser_validations(false by default), restarted rails but remain the same input:
<input autofocus="autofocus" class="string email optional form-control
input-xlarge" id="customer_email" maxlength="255"
name="customer[email]" pattern="\A[^#\s]+#([^#\s]+\.)+[^#\s]+\z"
size="255" type="email">
have tried also to add on form html: {novalidate: true}, same output
finally have tried to add on input_filed :novalidate => true, the html output change to:
<input autofocus="autofocus" class="string email optional form-control
input-xlarge" id="customer_email" maxlength="255"
name="customer[email]" pattern="\A[^#\s]+#([^#\s]+\.)+[^#\s]+\z"
size="255" type="email" novalidate="novalidate">
but browser validation and chrome error is present.
Any idea to resolve?
PS: Use Bootstrap and the login form is from Devise resource.
You can remove the pattern attribute from the input element that is causing a problem. You just need to set pattern: false on the input field.
So your input field might look something like this:
<%= f.input_field :email, type: 'email', required: true, autofocus: true, class: 'form-control', pattern: false %>
(nil doesn't work; it has to be false.)
This worked for me in Rails 4.
Forgive me if this seems like a simple task, I'm fairly new to this...
I'd like to create logic that allows the user to display or not display their email address when editing it from a dialog box. I am placing the link that will allow the user to 'opt out' inside the dialog box - and I'm trying to use the link to reset the variable inside the 'if' statement to 'false' The 'if' statement prevents the email address from being rendered.
Here is my if statement:
<div id="change-email" class="text">
#{
var showEmail = true;
if (showEmail == true)
{
<text><p><span class="label">My email address: </span>#Model.Email</p></text>
}
else (showEmail == false)
{
<text><p>No email displayed</p></text>
}
}
</div><!--#change-email-->
And here is the dialog box code:
<div id="dialog-email" class="modal">
#using (Html.BeginForm("ChangeEmail", "Account", FormMethod.Post))
{
<fieldset>
// form code here
</fieldset>
}
<p>Do not display my email address.</p>
</div>
Any help would be appreciated...
Thanks!
If you do this with jQuery, and you were okay with the email address still being available in the page source, it would look like this:
<div id="change-email" class="text">
<p><span class="label">My email address: </span>#Model.Email</p>
</div>
<div id="dialog-email" class="modal">
#using (Html.BeginForm("ChangeEmail", "Account", FormMethod.Post))
{
<fieldset>
// form code here
</fieldset>
}
<p>Do not display my email address.</p>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('a.no-display').click(function(){
$('#change-email p').text('No email displayed.');
});
});
</script>
It would be a bit more involved if you wanted to persist the preference to not display email. You would probably want to add "Do not display my email address" as a check-box in the ChangeEmail form, adjust the Controller Action to which the form posts to handle the preference, and return it as a variable in the ViewBag of the View that the Action returns.
Have: Using ASP.NET MVC 2, DataAnnotationsModel based server validation, and client validation with jQuery. Anything in my model is validated perfectly on the client with jQuery based validation (jQuery.validate and MicrosoftMvcJQueryValidation.js).
Need: Adding an additional HTML <input type="checkbox" id="terms" /> to my form. I need jQuery validation to require that this checkbox is checked AND somehow hook it in with whatever jQuery client script MVC is automagically controlling. Yes, I know it won't validate on the server side, but I don't need or want it to.
Seems like it should be simple but I'm new to MVC, a total beginner at jQuery, and my searches have been coming up blank.
Any help would be appreciated!
Here's a solution. It mimics what mvc does to hook into jQuery validation. So there's a checkbox called Accept that doesn't belong to the model. The script must go after the form and it adds all the validation meta data for that field.
<%
Html.EnableClientValidation(); %>
<% using(Html.BeginForm("Show"))
{ %>
<%= Html.EditorForModel() %>
<div class="editor-field">
<%= Html.CheckBox("Accept", new { #class = "required" })%>
<span class="field-validation-valid" id="Accept_validationMessage"></span>
</div>
<input type="submit" value="Submit" />
<%} %>
<script type="text/javascript">
window.mvcClientValidationMetadata[0].Fields.push({
FieldName: "Accept",
ReplaceValidationMessageContents: true,
ValidationMessageId: "Accept_validationMessage",
ValidationRules: [{ ErrorMessage: "The Accept field is required.", ValidationType: "required", ValidationParameters: {}}]
});
</script>
Might I suggest using a ViewModel for every View (put all of your dataannotations in there). Then you can create a boolean model property for your checkbox and set it to required.
From there, if you're posting the model back to the controller, you can simply use AutoMapper to map the ViewModel to the needed model, or simply map the properties yourself.
Either way, it is good practice to use a ViewModel for every view. Remember a ViewModel's job is to try and contain everything required in the view. This definitely means that it can and will have other data that is not required in the Model.
Try this
$(document).ready(function() {
//// Assuming your form's ID is 'form0'
$("#form0").submit(function() {
if ($("#terms").attr('checked')) {
return true;
}
else
{
//// Error message if any
return false;
}
});
});
I've got a form with two sections. Each section expands by its own radio button, so there's only one visible section at a time. And I use ASP.NET MVC HtmlHelper to generate fields like so:
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type1" id="type1" /> Label1
</label>
<%= Html.TextBox("Field1", Model.IntProperty1) %>
<label for="type-permanent" class="radio active">
<input type="radio" name="Type" value="Type2" id="type2" /> Label2
</label>
<%= Html.TextBox("Field2", Model.IntProperty2) %>
I also have two functions so that I could determine, which section is active:
function isType1() { return $("#type1").attr("checked"); }
function isType2() { return $("#type2").attr("checked"); }
Finally, I've got the followind validation methods set up:
Field1: {
required: isType1,
min: 1
},
Field2: {
required: isType2,
min: 1
}
Now, the point is that if I pass empty model to the view, both fields are set to 0 (default for int). Now if the user fills some fields and tries to submit the form, there is validation error, because even though the field in other section is not required, but it has the value - 0, which is not correct since it must be more that 1. How can I overcome this except clearing fields in hidden sections before form submission?
UPDATE. I guess I need some kind of conditional validation method.
If you can build it in, the required method takes a callback, so maybe you can build in the zero null check into the required validator via: http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-callback
HTH.