Validating User Input for Letters - validation

I've recently been trying to validate a user input so that only letters from the alphabet are accepted, how would I do this? I know how to validate user input for most things, but this one line of code for letters is really troubling me.

You can check the contents of a field with this function:
function validate theString
return matchText(theString,"^[a-zA-Z]+$")
end validate
^[a-zA-Z]+$ is a regular expression. ^indicates the beginning of a string, the brackets equal one char and the expression inside the bracket determine a set of characters. The + means that all following characters have to be equal to the preceding (set of) character(s). The $ indicates the end of the string. In other words, according to this expression, all characters must be of the set a up to and including z or A up to and including Z.
matchText() is a LiveCode function, which checks if the string in the first parameter matches the regular expression in the second parameter. Put the validate() function somewhere at card or stack level and call it from a field in a rawKeyUp handler:
on rawKeyUp
if not validate(the text of me) then
beep
answer "Sorry, that's wrong"
end if
end rawKeyUp
You could also check beforehand:
on keyDown theKey
if validate(theKey) then
pass keyDown
end if
end keyDown
This method is slightly verbose. You could also put the matchText function in a keyDown handler of your field.

Related

padding the middle of a string

I have a Textbox field that takes in a string with a character limit of 10. I would like to implement a short hand version because there are a lot of zeros in the string that have to be entered. so an example of the string is T000028999. but id like to key in T28999 and have the zeros padded between the "T" and the "28999" and show up as the T000028999 string in the Textbox field.
Is this even possible?
I've tried searching examples on google and have only found ways to pad the beginning and end of the string.
You want to keep the first character, so you can use oldString.Chars(0) to get that.
You want the remainder of the string: oldString.Substring(1), and you can pad it to the width you require with a character of your choice with PadLeft, like this:
Dim newString = oldString.Chars(0) & oldString.Substring(1).PadLeft(9, "0"c)
It would be a good idea to check that oldString is at least 1 character long before doing that otherwise the .Chars(0) will give an error.
Alternatively you could insert a new string of the required quantity of "0"s:
Dim newString = oldString.Insert(1, New String("0"c, 10 - oldString.Length))
A good place to perform the formatting would be in the control's Validating event handler. (The TextChanged event handler would not be a good place because it would interfere with the user's typing.)
Refs:
String.Chars[Int32] Property
String.Substring Method
String.PadLeft Method
String.Insert(Int32, String) Method
String Constructors

how to document a single space character within a string in reST/Sphinx?

I've gotten lost in an edge case of sorts. I'm working on a conversion of some old plaintext documentation to reST/Sphinx format, with the intent of outputting to a few formats (including HTML and text) from there. Some of the documented functions are for dealing with bitstrings, and a common case within these is a sentence like the following: Starting character is the blank " " which has the value 0.
I tried writing this as an inline literal the following ways: Starting character is the blank `` `` which has the value 0. or Starting character is the blank :literal:` ` which has the value 0. but there are a few problems with how these end up working:
reST syntax objects to a whitespace immediately inside of the literal, and it doesn't get recognized.
The above can be "fixed"--it looks correct in the HTML () and plaintext (" ") output--with a non-breaking space character inside the literal, but technically this is a lie in our case, and if a user copied this character, they wouldn't be copying what they expect.
The space can be wrapped in regular quotes, which allows the literal to be properly recognized, and while the output in HTML is probably fine (" "), in plaintext it ends up double-quoted as "" "".
In both 2/3 above, if the literal falls on the wrap boundary, the plaintext writer (which uses textwrap) will gladly wrap inside the literal and trim the space because it's at the start/end of the line.
I feel like I'm missing something; is there a good way to handle this?
Try using the unicode character codes. If I understand your question, this should work.
Here is a "|space|" and a non-breaking space (|nbspc|)
.. |space| unicode:: U+0020 .. space
.. |nbspc| unicode:: U+00A0 .. non-breaking space
You should see:
Here is a “ ” and a non-breaking space ( )
I was hoping to get out of this without needing custom code to handle it, but, alas, I haven't found a way to do so. I'll wait a few more days before I accept this answer in case someone has a better idea. The code below isn't complete, nor am I sure it's "done" (will sort out exactly what it should look like during our review process) but the basics are intact.
There are two main components to the approach:
introduce a char role which expects the unicode name of a character as its argument, and which produces an inline description of the character while wrapping the character itself in an inline literal node.
modify the text-wrapper Sphinx uses so that it won't break at the space.
Here's the code:
class TextWrapperDeux(TextWrapper):
_wordsep_re = re.compile(
r'((?<!`)\s+(?!`)|' # whitespace not between backticks
r'(?<=\s)(?::[a-z-]+:)`\S+|' # interpreted text start
r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words
r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash
#property
def wordsep_re(self):
return self._wordsep_re
def char_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Describe a character given by unicode name.
e.g., :char:`SPACE` -> "char:` `(U+00020 SPACE)"
"""
try:
character = nodes.unicodedata.lookup(text)
except KeyError:
msg = inliner.reporter.error(
':char: argument %s must be valid unicode name at line %d' % (text, lineno))
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
describe_char = "(U+%05X %s)" % (ord(character), text)
char = nodes.inline("char:", "char:", nodes.literal(character, character))
char += nodes.inline(describe_char, describe_char)
return [char], []
def setup(app):
app.add_role('char', char_role)
The code above lacks some glue to actually force the use of the new TextWrapper, imports, etc. When a full version settles out I may try to find a meaningful way to republish it; if so I'll link it here.
Markup: Starting character is the :char:`SPACE` which has the value 0.
It'll produce plaintext output like this: Starting character is the char:` `(U+00020 SPACE) which has the value 0.
And HTML output like: Starting character is the <span>char:<code class="docutils literal"> </code><span>(U+00020 SPACE)</span></span> which has the value 0.
The HTML output ends up looking roughly like: Starting character is the char:(U+00020 SPACE) which has the value 0.

Django alpha numeric validation in form fields

I want to perform a field validation,but the conditions are
1)The field should have 10 character.
2)off these 1st 5 character should be alphabets and next 5 character should be numeric digits
I performed validation for maximum length check,but rest of the thing how to perform.Is that can be done on a single "if" condition.
I am searching for the logic in google for performing that,but not got any idea.Can any one help me to perform the same.
forms.py for length check
def clean_bookref(self):
cd=self.cleaned_data
bookref=cd.get('bookref')
if len(bookref)<10 and re.match(r'[A-z0-9]+', bookref):
raise forms.ValidationError("Should be 10 digits")
return bookref
I am using this code to do but it is not working.
Thanks
Perhaps you could use something like his:
def clean_bookref(self):
cd=self.cleaned_data
bookref=cd.get('bookref')
if not re.match(r'^[A-Za-z]{5}[0-9]{5}$',bookref) :
raise forms.ValidationError("Should be of the form abcde12345")
return bookref

What does this Ruby line say?

I am working with a custom renderer, and I used some copy paste from another site. I can't seem to figure out what this piece is doing right here.
"#{options[:callback]}(#{data})"
Here is the piece of code in full context.
ActionController.add_renderer :as3 do |data, options|
data = ActiveSupport::JSON.encode(data) unless data.respond_to?(:to_str)
data = "#{options[:callback]}(#{data})" unless options[:callback].blank?
self.content_type ||= Mime::JSON
self.response_body = data
end
It's simple string interpolation. It will produce a string like this, where callback is the value of options[:callback], and value is whatever is in the variable data.
"callback(value)"
In Ruby, double-quoted strings support interpolation via #{} syntax. That is, if you have a variable x containing the value 3, the string "The value of x is #{x}" will be evaluated to "The value of x is 3". Inside a #{} you can have any arbitrarily complex Ruby expression, including array/hash indexing. So, the first part of the string, "#{options[:callback]}" is simply substituting the value of options[:callback] into the string.
The next part, the () is simply raw string data, not executable code. Inside the (), you have a second #{} substitution of data. It might be clearer if you replace the two variable substituions with x and y:
x = 3
y = 4
"#{ x }(#{ y })"
The above will evaluate to the string "3(4)"
This is converting a JSON response to JSONP; imagine data is:
'{"some": "thing", "goes": "here"}'
JSONP states that the data should be wrapped in a JavaScript function call. So of options[:callback] is the string test (the name of the function to call), the resulting JSONP would be:
'test({"some": "thing", "goes": "here"})'
It's a template that replaces the first field with the value of options poiinted to by the interned string :callback, and the second field, inside the parens with the contents of data.
I'd bet a buck that the resulting string is going to be eval'd somewhere else, where it will become a call to a procedure. That would work something like this:
options[:callback] = "foo"
data="arg,arg,arg"
(Notice that data is being encoded into JSON, so the string passed as data is a json string.
The string then turns into "foo(arg.arg.arg)", and when it's eval'd it becomes a call to routine foo with those arguments.
http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-eval
Update:
Actually, I take it back about the Ruby eval -- although that would work, it's more likely turning into a Javascript function call. This would then let you pass the name of a javascript function as a string and the code would return the appropriate callback function for execution by javascript later.
You can rewrite
"#{options[:callback]}(#{data})"
as
options[:callback].to_s + "(" + data.to_s + ")"

Ruby: String Comparison Issues

I'm currently learning Ruby, and am enjoying most everything except a small string comparason issue.
answer = gets()
if (answer == "M")
print("Please enter how many numbers you'd like to multiply: ")
elsif (answer. == "A")
print("Please enter how many numbers you'd like to sum: ")
else
print("Invalid answer.")
print("\n")
return 0
end
What I'm doing is I'm using gets() to test whether the user wants to multiply their input or add it (I've tested both functions; they work), which I later get with some more input functions and float translations (which also work).
What happens is that I enter A and I get "Invalid answer."The same happens with M.
What is happening here? (I've also used .eql? (sp), that returns bubcus as well)
gets returns the entire string entered, including the newline, so when they type "M" and press enter the string you get back is "M\n". To get rid of the trailing newline, use String#chomp, i.e replace your first line with answer = gets.chomp.
The issue is that Ruby is including the carriage return in the value.
Change your first line to:
answer = gets().strip
And your script will run as expected.
Also, you should use puts instead of two print statements as puts auto adds the newline character.
your answer is getting returned with a carriage return appended. So input "A" is never equal to "A", but "A(return)"
You can see this if you change your reject line to print("Invalid answer.[#{answer}]"). You could also change your comparison to if (answer.chomp == ..)
I've never used gets put I think if you hit enter your variable answer will probably contain the '\n' try calling .chomp to remove it.
Add a newline when you check your answer...
answer == "M\n"
answer == "A\n"
Or chomp your string first: answer = gets.chomp

Resources