I cannot find the right answer for my case, so I posted my question here.
I'm validating the form in ASP.NET MVC and looking for the way to validate a text field to allow only numeric and decimal numbers like
1 or 1.5 or 1.65
If I have 1,65 I do not want this to be validated.
I have put a metadata on my Model's field like this: [RegularExpression(#"^(((\d{1})*))$")]
And have
#Html.ValidationMessageFor(m => m.ResolvedAmount, "", new { #class = "error" })
to validate the field.
Also, in my function I have the following to check the validation:
var validator = $("#main").kendoValidator().data('kendoValidator');
if(validator.validate()){some logic}
I validate for the required field, but cannot get my int/decimal validation working.
What do I need to have in order to validate it?
Related
I am new in Laravel I want to need some validation if I checked checkbox then in front of input field will validate Required|Numeric|min:1
Please Help.
As per below image
You are looking for required_if.
So, you could have the following rules in your Form Request or your Validator.
return [
'systolic_blood_pressure_high' => 'nullable|numeric|min:1|required_if:has_systolic_bp,on',
'systolic_blood_pressure_low' => 'nullable|numeric|min:1|required_if:has_systolic_bp,on',
];
Assuming you have a checkbox with name has_systolic_bp and it is checked, the fields systolic_blood_pressure_high and systolic_blood_pressure_low will be required.
You also need to mark them as nullable as by default Laravel will consider them as invalid because of the TrimStrings and ConvertEmptyStringsToNull middlewares.
For more information, check the documentation
I'm writing a .NET MVC application and using unobtrusive validation to sanitize my client inputs based on data annotations in my model. I have an input that I do not want to allow HTML tags into and would like to display a custom error message if an html tag is entered. As such I have created a data annotation with a custom regex expression to cover these conditions, like so:
[Required(ErrorMessage = "You must provide a First Name.")]
[RegularExpression(#"<[a-z][\s\S]*>", ErrorMessage = "Invalid character")]
[DisplayName("First Name")]
public string FirstName { get; set; }
The issue with this is, no matter what character, whether it be <test> or whether it be abc will cause the Invalid Character message to appear. The required attribute works fine, and if I try a simple regex such as:
[RegularExpression("[a-z]", ErrorMessage = "Invalid character")]
This works 100% as expected, leading me to believe my regex is incorrect, nut I know it works for HTML validation as I can prove it out with online tools. What am I doing wrong?
If you take a look at the documentation of the RegularExpressionAttribute, it states:
Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.
So your attribute is doing the exact opposite of what you want to do is:
[RegularExpression(#"^(?!.*<.*>).*$", ErrorMessage = "Invalid character")]
I have a template with an input field. The input field uses a timepicker plugin which uses a format like "1:00 AM" or "4:30 PM".
In forms.py, ive tried:
timepicker = forms.TimeField(label='Time', widget=forms.TimeInput(format='%H:%M %p'))
timepicker = forms.TimeField(label='Time', widget=forms.TimeInput(format='%I:%M %p'))
But with both these snippets, i continue to get a input validation error that says it does not match the format.
Have you tried the following?
forms.TimeField(label='time',
input_formats=['%I:%M %p'],
widget=forms.TimeInput(format='%I:%M %p'))
I am new to Play 2.3.x and Scala and trying to implement a form input validation.
Let us say I have an example form.
val userForm = Form(
"firstName" -> nonEmptyText
)
I want to implement something like this for the first name field:
If a regex for first name (say firstName.regex = “regex for first name” ) is defined then {
Validate first name against specific regex
}else{
Validate against the global regex ( say global.regex = “global regex white list some regex valid for across the application”)
}
Also, I want to combine this with multiple (chained/step wise) validations so as to be able to display :
If nothing is entered - Please First name
If first name is enetred and fails regex validation - Please enter a valid first name
I want to develop a generic solution so that I can use it for all the fields.
Appreciate any help.
You can use verifying.
val userForm = Form(
"firstName" -> nonEmptyText.verifying("Must contain letters and spaces only.", name => name.isEmpty || name.matches("[A-z\\s]+") )
)
There's a little extra logic there (name.isEmpty with OR), because an empty string would trigger both validation errors. It seems like the validation errors are kept in order in which they're triggered, so you might be able to get away with using the first validation error in the sequence, but don't hold me to that. You can chain as many verifyings together as you like.
I'm not entirely sure what you have in mind by making these more generic, but you can make your own Mapping validators by composing already existing ones in the Forms object.
val nonEmptyAlphaText: Mapping[String] = nonEmptyText.verifying("Must contain letters and spaces only.", name => name.matches("[A-z\\s]+") )
And then you can use it in the Form:
val userForm = Form(
"firstName" -> nonEmptyAlphaText
)
Given the following models (cut down for understanding):
class Venue(models.Model):
name = models.CharField(unique=True)
class Band(models.Model):
name = models.CharField(unique=True)
class Event(models.Model):
name = models.CharField(max_length=50, unique=True)
bands = models.ManyToManyField(Band)
venue = models.ForeignKey(Venue)
start = models.DateField()
end = models.DateField()
The admin area works great for what I'm doing, but I'd like to open the site up a bit so that certain users can add new Events. For the public portions, I have several "administrative" fields on these models that I don't want the public to see (which is easy enough to fix).
My specific problem, though, is changing the display of the ManyToMany selections when creating a new Event. Because the number of Bands possible to list for an event should not be sent along as a multiselect box, I'd like to use an AutoComplete that handles multiples (like the Tags box, here on StackOverflow!).
I have this part working, and it correctly fills in a hidden input with the Band.id's separated by commas for a value. However, I can't understand how to put together letting Django do the validation using the ModelForms, and somehow also validating the 'Bands' selection.
Ideally, I want to auto-complete like the tags here on StackOverflow, and send along the selected Bands ID's in some kind of Delimited string - all while letting Django validate that the bands passed exist, etc, as if I left the annoying multi-select list in place.
Do I have to create my own Auto-Complete Field type for a form or model, and use that? Is there something else I'm overlooking?
I have seen some existing AutoComplete widgets, but I'd really-really-really like to use my own Autocomplete code, since it's already set up, and some of them look a bit convoluted.
There was a lot more text/explanation here, but I cut back because I'm avoiding Wall Of Text. If I left important stuff out, let me know.
It's a little hard to say without knowing exactly what your autocomplete code is doing, but as long as it is sending the ids of the bands like they would be sent with the <select>, the ModelForm should validate them as usual.
Basically, your POST string should look like:
name=FooBar2009&bands=1&bands=3&bands=4&venue=7&start=...
The easiest way to do this might be to use Javascript to add (and remove) a hidden input field for each band entered with the name band and the id of the band as the value. Then, when the user submits the form, the browser will take care of posting the right stuff, and the ModelForm will validate it.
Using the annointed jquery autocomplete plugin,
On the client-side I have something like this:
jQuery("#id_tags").autocomplete('/tagging_utils/autocomplete/tasks/task/', {
max: 10,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300,
matchContains: true,
autoFill: true,
});
So, I have a view that returns when I type in a:
http://skyl.org/tagging_utils/autocomplete/tasks/task/?q=a&limit=10×tamp=1259652876009
You can see the view that serves that here:
http://github.com/skyl/skyl.org/blob/master/apps/tagging_utils/views.py
Now, it's going to be a little tricky .. you might except the POST, then in the clean method of the field try to .get() based on the strings and raise a form validation error if you can't get it ... right, name = ... unique=True .. so something like (off the top of my head) ... :
def clean_bands(self):
return Band.objects.filter( name__in = self.cleaned_data['bands'].split(' ') )
You could also check each string and raise a form error if there are no bands by that name .. not sure that the clean method should return a qs. Let me know if this helps and you want me to keep going/clarify.