Model Validation to allow only alphabet characters in textbox - asp.net-mvc-3

How can I annotate my model so I can allow only alphabets like A-Z in my text-box?
I know that I can use regex but can anyone show how to do that on text-box property itself using data annotation.

You could annotate your model like this:
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
string TextBoxData {get; set;}
Then in your view you would use the helper
#Html.EditorFor(model => model.TextBoxData)
#Html.ValidationMessageFor(model => model.TextBoxData )

You can use annotations for regular expression validation (if i understood your questions), something like that
[RegularExpression("[a-zA-Z]",ErrorMessage="only alphabet")]

You could write like this
It matches First character must be an alpha word
and following that matches any number of characters/hyphen/underscore/space
[RegularExpression(#"^[a-zA-Z]+[ a-zA-Z-_]*$", ErrorMessage = "Use Characters only")]

Related

How to get elements matching a partial text

I'm using NEST to create services, so I can search into a field (label)
Is there a way to get answers from a partial string ?
For example, if I have three labels : "John Doe" , "Dadido" and "Unicorn", if I type "Do", I get the two first ones
For now, I have this :
elasticClient.Search<ESbase>(s => s.Query(q=>q.Regexp(c =>
c.Name("label_query")
.Field(p =>p.Label).Value('*'+label+'*'))));
And when I try it, it doesn't send anything back
match: { text: '.*label.*'}should work
If you want use regex: Value(".*label.*")
I assume you used default maping and in your label string you dont have special character.
Edit: use wildcard work too .Wildcard("*label*")

How to use regex to match for number and string? [duplicate]

I have some IDs 214001, 214002, 215001, etc...
From a searchbar, I want autocompletion with the ID
"214" should trigger autocompletion for IDs 214001, 214002
Apparently, I can't just do a
scope :by_number, ->(number){
where(:number => /#{number.to_i}/i)
}
with mongoid. Anyone know a working way of matching a mongoid Integer field with a regex ?
This question had some clue, but how can I do this inside Rails ?
EDIT : The context is to be able to find a project by its integer ID or its short description :
scope :by_intitule, ->(regex){
where(:intitule => /#{Regexp.escape(regex)}/i)
}
# TODO : Not working !!!!
scope :by_number, ->(numero){
where(:number => /#{number.to_i}/i)
}
scope :by_name, ->(regex){
any_of([by_number(regex).selector, by_intitule(regex).selector])
}
The MongoDB solution from the linked question would be:
db.models.find({ $where: '/^124/.test(this.number)' })
Things that you hand to find map pretty much one-to-one to Mongoid:
where(:$where => "/^#{numero.to_i}/.test(this.number)")
The to_i call should make string interpolation okay for this limited case.
Keep in mind that this is a pretty horrific thing to do to your database: it can't use indexes, it will scan every single document in the collection, ...
You might be better off using a string field so that you can do normal regex matching. I'm pretty sure MongoDB will be able to use an index if you anchor your regex at the beginning too. If you really need it to be a number inside the database then you could always store it as both an Integer and a String field:
field :number, :type => Integer
field :number_s, :type => String
and then have some hooks to keep :number_s up to date as :number changes. If you did this, your pattern matching scope would look at :number_s. Precomputing and duplicating data like this is pretty common with MongoDB so you shouldn't feel bad about it.
The way to do a $where in mongoid is using Criteria#for_js
Something like this
Model.for_js("new RegExp(number).test(this.int_field)", number: 763)

Ruby string index with escaped double quotes

I'm trying to split a string email that contains HTML content into 2 parts, one before <div class=\"gmail_signature\"> and one after.
EDIT: Here's a sample of what's in email:
My email is here<div class=\"gmail_quote\">and my signature</div>
So I'd like to have My email is here and <div class=\"gmail_quote\">and my signature</div> separately.
Using email.index('<div class=\"gmail_signature\">') returns nil, because of the \". The same issue happens with gsub.
What's the best way to deal with this?
Thanks!
email = 'aaa<div class="gmail_signature">bbb'
=> "aaa<div class=\"gmail_signature\">bbb"
email.split('<div class="gmail_signature">')
=> ["aaa", "bbb"]

MaxLength attribute and unobtrusive validation

If I add a MaxLengthAttribute to a property like this:
[MaxLength]
[DataType(DataType.MultilineText)]
public string Notes { get; set; }
The markup is rendered like this:
<textarea class="form-control" data-bind="value: Notes" data-val="true" data-val-maxlength="The field Notes must be a string or array type with a maximum length of '-1'." data-val-maxlength-max="-1" id="Notes" name="Notes"></textarea>
and the validation result looks something like this:
This is obviously not the intended result. The text area should allow A LOT more characters than '-1'.
I can think of multiple ways of addressing this (e.g. removing the attribute via jQuery, manually updating the rule with javascript, etc).
What is the most elegant way of addressing this issue? Is this a bug with MVC/Validator
You are not specifying the desired maximum length of the string, what do you expect? This overload of the MaxLength attributes takes an integer as argument which specifies the actual maximum allowed length of the string. When you use the parameter-less constructor it will use the maximum length allowed by the database, not sure why jQuery Validation chose to implement this as -1 though.

ASP.NET MVC 3 Lambda (=>) Syntax

Please, can anyone tell me what the meaning of => operator in Html helper syntax.
Eg: #Html.TextBoxFor(m => m.UserName)
It's not specific to the Razor engine. That is a C# lambda expression.
m => m.Username is equivalent to providing a method, something like
string GetUserName(TypeOfModel m)
{
return m.UserName;
}
However, because TextBoxFor takes an Expression, it is able to 'parse' the lambda and is able to infer that the name of the TextBox input should be 'Name' (viz the property scraped off the model). This is important and 'intuitive', since the MVC ModelBinder will then be able to map "Name" to a property or parameter when it is next sent back to a controller.

Resources