Simplest input validation using Char.IsNumber and Char.IsLetter

The following example demonstrates how to validate a user input by using the Char.IsNumber and Char.IsLetter character manipulation functions:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a font  
  10. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  11. 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)  
  12. //creates our controls  
  13. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 170))    
  14. let okbutton=new Button(Text="Ok", Location=new System.Drawing.Point(100, 170))   
  15. let label1=new Label(Text="Enter a name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  16. let nametxtbox=new TextBox(Location=new System.Drawing.Point(120,10),BorderStyle=BorderStyle.FixedSingle)  
  17. validateform.Font<-ffont  
  18. //adds the controls to our form  
  19. validateform.Controls.Add(exitbutton)  
  20. validateform.Controls.Add(okbutton)  
  21. validateform.Controls.Add(label1)  
  22. validateform.Controls.Add(nametxtbox)  
  23. //when the oK button is clicked  
  24. okbutton.Click.Add(fun ok->  
  25. //if the input begins with a letter then  
  26. if (Char.IsLetter(Convert.ToChar(nametxtbox.Text.Chars(0)))) then  
  27. //prompt that its a valid name  
  28. MessageBox.Show("The name you entered is valid ""Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore  
  29. //if the input begins with a number then                           
  30. if (Char.IsNumber(Convert.ToChar(nametxtbox.Text.Chars(0)))) then  
  31. //prompt that its an invalid name  
  32. MessageBox.Show("You must enter a valid name""Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore)  
  33. //when the exit button is clicked  
  34. exitbutton.Click.Add(fun exit->validateform.Close())  
  35. //executes our application  
  36. 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: