Simplest input validation using Char.IsNumber and Char.IsLetter

Posted by Rey Dacoco in

The following example demonstrates how to validate a user input by using the Char.IsNumber and Char.IsLetter character manipulation functions:

// Learn more about F# at http://fsharp.net
//specifies the memory location of the class files
//that will be needed in our application
open System.Collections.Generic
open System
open System.Windows.Forms
open System.ComponentModel
open System.Drawing
//creates a font
let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)  
let validateform = new Form(Text="Validate Inputs",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)
//creates our controls
let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 170))  
let okbutton=new Button(Text="Ok", Location=new System.Drawing.Point(100, 170)) 
let label1=new Label(Text="Enter a name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)
let nametxtbox=new TextBox(Location=new System.Drawing.Point(120,10),BorderStyle=BorderStyle.FixedSingle)
validateform.Font<-ffont
//adds the controls to our form
validateform.Controls.Add(exitbutton)
validateform.Controls.Add(okbutton)
validateform.Controls.Add(label1)
validateform.Controls.Add(nametxtbox)
//when the oK button is clicked
okbutton.Click.Add(fun ok->
//if the input begins with a letter then
if (Char.IsLetter(Convert.ToChar(nametxtbox.Text.Chars(0)))) then
//prompt that its a valid name
MessageBox.Show("The name you entered is valid ", "Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore
//if the input begins with a number then                         
if (Char.IsNumber(Convert.ToChar(nametxtbox.Text.Chars(0)))) then
//prompt that its an invalid name
MessageBox.Show("You must enter a valid name", "Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore)
//when the exit button is clicked
exitbutton.Click.Add(fun exit->validateform.Close())
//executes our application
Application.Run(validateform)
Click the run icon when done entering these codes in Visual F# code editor window. Try entering any number in the name text box and clicking the ok button. You should see an output similar to the following:

0 comments

Post a Comment

Contributor

My photo
I am just a simple man with a simple mind. And this is my simple blog. New Posts will be available soon. Enjoy reading and never stop learning:)

Total Pageviews

Link List

Archives

Got questions? You can reach me here: