Say I have a dynamic form like this.
How can I validate my users fields to ensure that there is at least one name is filled before user submit the form?
I try to add rules into the Form.List but it is not working.
Adding custom validator to the individual user component only allow me to have access to that particular name component so I can't check the length of the name array.
Manage to make it works by adding this to the rules:
({ getFieldValue }) => ({
validator() {
if (getFieldValue("users").length > 1) {
return Promise.resolve();
}
return Promise.reject(
"Please add at least 2 options"
);
}
})
Check here
Related
Hi I have just started Vaadin 7 and have got the BeanValidator working. But, I have some issues. The code I am using is the following:
BeanItem<RegisterBean> item = new BeanItem<RegisterBean>(new RegisterBean());
final FieldGroup binder = new FieldGroup(item);
final TextField email = new TextField("email");
email.addValidator(new BeanValidator(RegisterBean.class, "email"));
The validates fine using the BeanValidator. With the #NotNull tag I am able to validate for Null values as well. However, I would like to give the user visual clues that the field in the form can't be left blank. For this, I used:
email.setRequired(true);
However, after adding the setRequired the BeanValidation for the form no longer works?
Is this a limitation?
How do I get around it?
You should probably rely on the bean validation itself and use the fieldgroup.
My model looks as follows:
#NotNull(message="Please enter a valid email address.")
#Email(message="Please enter a valid email address.")
#Size(min = 3, max = 255, message="Please enter a valid email address.")
#Column(name="P_EMAIL", nullable=true, length=255)
private String email;
In your view do either buildAndBind
Field<?> email = binder.buildAndBind("email");
Or use the annotation #PropertyId("email") in your field declaration. The rest is magic.
Instead of FieldGroupuse BeanFieldGroup.
A problem will be that validation is made preliminary. So install the validators on click. More to that topic can be found here: http://morevaadin.com/content/bean-validation-and-vaadin-comprehensive-example/
To complete the example above, using a BeanFieldGroup, as it got validators, you can use the setValidationVisible method of an AbstractField to turn off preliminary validation, then to turn on in a blurListener and in the buttons clickListeners.
AbstractTextField cName = binder.buildAndBind("Name","name", AbstractTextField.class);
cName.setNullRepresentation("");
cName.setValidationVisible(false);
cName.addBlurListener(new MyBlurListener(cName)); //<-- turn on setValidationVisible there
myButton.addClickListener(event -> {
try {
cName.setValidationVisible(true);
binder.commit();
} catch (CommitException e){
Notification.show("Sending error");
}
});
I'm using grails JQuery Validation UI Plugin for grails 2.1.0.
I nearly have my form valadting client side based on my command object constraints.
There is one problem, I have a custom constraint in my command object:
startTime(nullable: false, validator: {startTime, deal ->
if ((!DateUtils.isSameDay(startTime, new Date()) && startTime.before(new Date()))) //Start date is today or future but not before end date
{
return "pastDate"
}
if (deal.endTime && startTime.after(deal.endTime)) {
return "before.endTime"
}
})
This results in the following rendered jQuery validation code generated with page markup:
startTime: {
date: true,
required: true,
validator: {
url: '/appContextRoot/JQueryRemoteValidator/validate',
type: 'post',
data: {
validatableClass: 'myapp.command.tester.testerDealCommand',
property: 'startTime'
}
}
}
The custum constrains logic withing "validator:" does nothing currently.
What is the best approach to get this custom validator working?
1: Some form of Ajax call?
2: Use Custom Constraits plugin and add js code to grails-validation-methods.js?
3: Some other way?
I'm unsure of using option 2....is there some way to extend the plugin?
I do not want to have to commit and maintain a seperate version of the plugin in our source code repository.
If I understood correctly the plugin, there's no need to add your custom validations directly to grails-validation-methods.js
If you load your script after, you can just follow his convention:
jQuery.validator.addMethod("myCustomValidation", function(value, element, params) {
//perform your validation here
}, "Custom validation fail.");
I have a page written using .NET MVC. In the model for a Person called PersonModel I have this defined which requires the user to enter some text in the last name field:
<DisplayName("Last Name"), Required()> _
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
On the form, there is a checkbox that a user can check to do some other things. Is there a way, using JQuery preferablly, to change that Last Name field to be non-Required? If not using JQuery I am open to other suggestions but since I am doing alot of things when this check box is checked anyways, I was hoping I could add this logic in there. Here is some sample of what I am doing when this box is checked to demonstrate...
function doOwnerBusiness(event) {
if ($(this).is(':checked')) {
$('input[name="People_1__LastName"], label[for="People[1]_LastName"]').hide();
$("#People_1__LastName").hide();
$("#People_1__LastName").val("");
$("#People_1__LastName :input").attr('disabled', true);
$('input[name="People[1]_Suffix"], label[for="People[1]_Suffix"]').hide();
$("#People_1__Suffix").attr('disabled', true);
$('#People_1__Suffix')[0].selectedIndex = 0;
$('#People_1__Suffix').hide();
}
else {
$('input[name="People_1__LastName"], label[for="People[1]_LastName"]').show();
$("#People_1__LastName").show();
$('#People_1__LastName :input').attr('disabled', false);
}
}
Any help with this would be appreciated folks.
Thank you
William
Here is how I am declaring my checkbox and also part of the function where I am trying to check if it is checked or not...
<%=Html.CheckBoxFor(Function(model) model.FirstNameAsBusiness)%>
<%=Html.LabelFor(Function(model) model.FirstNameAsBusiness)%>
Function Nominate(ByVal m As NominationModel, ByVal captchaValid As Boolean) As ActionResult
If Not m.FirstNameAsBusiness.checked AndAlso String.IsNullOrEmpty(m.lastnametext) Then
ModelState.AddModelError("LastName", "Last Name field is required if you don't yada yada...")
Return View()
End If
Short answer: no. You can't bypass the DataAnnotation with a jQuery call.
Technically, the Last Name field isn't required. So, I'd remove the DataAnnotation for Required, and then on the backend, when the user submits the form, verify that a field value exists when the checkbox isn't checked. If the conditional doesn't pass, and an error to ModelState for that field, and redirect to the page. (apologies for the c#):
public ActionResult Index(HomeIndexModel form)
{
if (!form.Checked && string.IsNullOrEmpty(form.LastName))
{
ModelState.AddModelError("LastName", "Last Name field is required if you don't yada yada...");
return View();
}
//conditional requirement passed...
}
If you want to get a little fancier, you can check out this thread, though all of the suggestions here are also server-side:
ASP.NET MVC Conditional validation
You know those fields you see on forms which indicate that a value can't be used because its already used? Like a username for a membership site.
I'd like to do this for an MVC form via jquery. What is the recommendation for this?
You could create a JsonResult action that you can call from your javascript code. Eg
public JsonResult IsUsernameAvailable(string username) {
// return result
return Json(true);
}
And then hook it up to your username-field like so using jQuery
$("#username").blur(function() { checkAvailability($(this).val()); });
function checkAvailability(username) {
$.getJSON("/User/IsUsernameAvailable", { username: username }, function(result) {
alert("Is available: " + result);
});
}
If you are using MVC 3 there is a new Remote attribute which you can use. You specify a route or controller/action for the attribute and return "true" or "false" (or any string != "true", which could be 'result' in your case. You will get a client side validation error similar to the errors you get if a required field is left blank etc.
I have a top-level page called ReceiveItem. Within that page, I have a couple different FORMs - only one of which will be filled out and submitted (depending upon how that item is received). This all works quite well from the UI perspective. Here is the general page structure:
<ReceiveItem.aspx>
<ReceiveNewInventory.ascx>
<ReceiveOrderReturn.ascx>
<ReceiveFromLoan.ascx>
Except, I do not know how to properly display validation errors. Here is my controller for one of those forms:
public ActionResult ReceiveNewInventory(
int id,
int vendorId,
int quantity,
decimal cost) {
var db = new Data();
var item = db.ItemSet.First(i => i.Id == id);
var vendor = db.BusinessSet.First(i => i.Id == vendorId);
ValidateCost(cost);
ValidateQuantity(quantity);
if (ModelState.IsValid) {
item.AddNewInventory(vendor, quantity, cost);
TempData["Message"] = "Added " + quantity +
" inventory items to " + item.FullDisplayName;
return RedirectToAction("Index");
}
else {
TempData["Quantity"] = quantity;
TempData["VendorId"] = vendorId;
TempData["Cost"] = cost;
return RedirectToAction("ReceiveItem", new { id });
}
}
I would like to display the model errors that the two validation functions add using the simple Html.ValidationSummary function; but, those errors seem to get lost because I do the RedirectToAction. (My ReceiveNewInventory controller action does not have a view directly associated with it.)
With the one condition that I still want 1 page with multiple FORMs, what can I change about this design so that my validation messages show up on the ReceiveItem page?
You need to put the ModelState into TempData and extract it in your ReceiveItem action method. Alternatively, change the Redirect to a return View()
hth
Dan
Look at NerdDinner and see how they do it. Very neat and you can display a summary at the top of the page as well as text next to each item if you wish.
let me know if you have trouble and I'll post code.
Why do you redirect to ReceiveItem even if you have errors? When you display the validation message, don't you want the user to have the opportunity to fix their mistakes? If so, why not keep them on the RecevieNewInventory page again and return the view?