Vaadin RegexpValidator multiple error message - regex

Is it possible to return conditional error message for a vaadin validator?
TextField textField = new TextField();
String regex = "?:(foo|bar)";
textField.addValidator(new RegexpValidator(regex, true, getErrorMessage()));
I want to have a different error message depending on what the user write in the textField.

I found the solution. One should just override the getErrorMessage of the validator
textField.addValidator(new RegexpValidator(regex, true, "") {
#Override
public String getErrorMessage() {
return setMessage();
}
});

Related

Hook to item selection action

When I select an item I want to check some fields before it will be displayed in the Field Editor and then change values on other fields.
So I need to subscribe to an event, but such event doesn't exist out of the box as I can see. Is there a way to hook to item selection action or I need to create a custom event, if so - where do I need to raise it?
Sounds like you need to create a custom validator - this blog post describes the process:
https://www.habaneroconsulting.com/stories/insights/2016/creating-a-custom-field-validator-in-sitecore
In summary:
Create a new field rule (Field validators are located in /sitecore/system/Settings/Validation Rules/Field Rules/) linking to your assembly. The blog post above gives the following example of a field validator
[Serializable]
namespace MySitecore.Project.Validators
{
// This validator ensures that the description attribute of a link is specified
public class LinkTextValidator : StandardValidator
{
public override string Name
{
get { return "Link text validator"; }
}
public LinkTextValidator() {}
public LinkTextValidator(SerializationInfo info, StreamingContext context) : base(info, context) { }
protected override ValidatorResult Evaluate()
{
Field field = this.GetField();
if (field == null)
return ValidatorResult.Valid;
string str1 = this.ControlValidationValue;
if (string.IsNullOrEmpty(str1) || string.Compare(str1, "<link>", StringComparison.InvariantCulture) == 0)
return ValidatorResult.Valid;
XmlValue xmlValue = new XmlValue(str1, "link");
string attribute = xmlValue.GetAttribute("text");
if (!string.IsNullOrEmpty(xmlValue.GetAttribute("text")))
return ValidatorResult.Valid;
this.Text = this.GetText("Description is missing in the link field \"{0}\".", field.DisplayName);
// return the failed result value defined in the parameters for this validator; if no Result parameter
// is defined, the default value FatalError will be used
return this.GetFailedResult(ValidatorResult.CriticalError);
}
protected override ValidatorResult GetMaxValidatorResult()
{
return this.GetFailedResult(ValidatorResult.Error);
}
}
}
Credit to: MICHAEL ARMSTRONG

Email regex not allowing null value

I'm using Angular and using this validator
public static validate(c: AbstractControl) {
const EMAIL_REGEXP = /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+#((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}
It does not allow me to have an empty value in input field.
What am I doing wrong?
Unless you have specific requirements, you can simply use the e-mail validator that Angular provides.
mailControl: FormControl = new FormControl('', [Validators.email]);
If you don't add a required validator, you will have the option to let it empty.

Get error message on isUnique attribute MVC

I have a model property like below,
[Index("CourseCodeIndex", IsUnique = true)]
[MaxLength(15)]
public string Name { get; set; }
and if I use invalid data it works well but returns no error message. Is there any way to show a message on (view, like other required like messages)
#Html.ValidationMessageFor(model => model.Name)
if you want to show the error message, you need to declare it like:
[Required(ErrorMessage = "Compiletime error required")]
Also, try this.
[Unique(ErrorMessage = "This already exist !!")]
Make an instance of your context file
private datbaseContext db = new databaseContext();
add the code below to your controller action method
db.table.Add(model);
var user = db.table.Where(u => u.Name == model.Name).FirstOrDefault();
if (user != null)
{
ModelState.AddModelError("", model.Name + " Already Exists");
}
else
{
db.SaveChanges();
return RedirectToAction("Index", "model");
}
And the #Html.ValidationSummary(true) from your view will attach the error message

How do I check if a view's model is correct?

I have an "Index" controller method which returns a view with a Model that is a List<WhatsNew>. I am trying to validate this method in a unit test but it gives me an error as it is expecting a string.
Controller
public ActionResult Index()
{
return View("Index", GetWhatsNew());
}
public List<WhatsNew> GetWhatsNew()
{
WCMSDataContext wcmsContext = new WCMSDataContext();
return (from p in wcmsContext.WhatsNews select p).ToList();
}
Unit Test
[TestMethod]
public void Validate_Index_IList_WhatsNew_AS_Model()
{
AppItemController controller = new AppItemController();
// Act
var result = controller.Index();
// Assert
var model = ((ViewResult)result).Model as List<WhatsNew>;
Assert.AreEqual("Index", model.ToList());
}
Error
Assert.AreEqual failed. Expected:<Index (System.String)>. Actual: <System.Collections.Generic.List`1[WCMS.WhatsNew]
You're comparing a string "Index" with a List<WhatsNew>:
Assert.AreEqual("Index", model.ToList());
What exactly are you expecting to happen here?
You can check the contents of the model:
Assert.AreEqual(someValue, model.Count);
Assert.AreEqual(someOtherValue, model[0].SomeProperty);
You can also check the right page is being returned in the action:
Assert.AreEqual("Index", ((ViewResult)result).ViewName);
At the moment, you seem to be trying to mix the two...
You may want to have a read of something like this as a basic introduction to checking your controllers.

Building Valdr custom validator

I have been trying since to build a custom validator using Valdr AngularJs plugin with no success.
What I want to archive is an input text that should receive date and time format like : dd/MM/yyyy hh:mm (12/04/2015 12:32:10)
Based on Valdr documentation, this is what I have done so far :
myApp.factory('customValidator', function () {
return {
name: 'customValidator', // this is the validator name that can be referenced from the constraints JSON
validate: function (value, arguments) {
// value: the value to validate
// arguments: the validator arguments
return value === arguments.onlyValidValue;
}
};
});
myApp.config(function(valdrProvider)
{
valdrProvider.addValidator('customValidator');
valdrProvider.addConstraints(
{
'Person':
{
'date_send':
{
'customValidator':
{
'onlyValidValue':'^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$|^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2}\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$',
'message': 'Please date and time format has to be : 12/04/2015 12:32:10'
}
}
}
});
});
Then in my form, I have the following :
<input class="input" name="date_send" id="date_send" type="text" ng-model="date_send" />
But it doesn't work.
I will appreciate any help.
Thank you !
If you only need a regex validator, I'd recommend to use the one provided by valdr instead of writing a custom validator:
valdrProvider.addConstraints({
'Person': {
'date_send': {
'pattern': {
'value': '^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$|^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2}\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$',
'message': 'Please date and time format has to be : 12/04/2015 12:32:10'
}
}
}
});
If you want a custom validator, you have to implement the validation logic in the validator. You just copied the sample validator from the docs, which only compares the users input value with the 'onlyValidValue' configured in the constraints. What you want to do is more like:
valdrProvider.addConstraints({
'Person': {
'date_send': {
'customDateValidator': {
'message': 'Please date and time format has to be : 12/04/2015 12:32:10'
}
}
}
});
Custom validator:
myApp.factory('customDateValidator', function () {
return {
name: 'customDateValidator',
validate: function (value, arguments) {
var dateCheck = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$|^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2}\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$/
return dateCheck.test(value);
}
};
});
I can't be 100% sure because you didn't provide enough code but I guess your input field declaration should be
ng-model="person.date_send"
rather than
ng-model="date_send"
For reference please have a look at the custom validator demo. It's always helpful if you can provide a plunker with a complete sample.