Search code examples
phpregexchess

Regular Expressions for validating chess-based input?


I'm working on a Chess-based hobby project with HTML/CSS/PHP. I wasn't familiar with chess beforehand, so I decided to make a tool that would show which moves were allowed based on the type and square of a given piece.

I have an HTML form with two text fields: one is for the type of the piece and the other one is for current square of said piece. Everything works, but I want to include validation using regular expressions.

The valid, case-insensitive inputs for the piece type are p, pawn, r, rook, b, bishop, n, knight, q, queen, k, king.

The valid, case-insensitive inputs for the square are LetterNumber where Letter can be A-H and Number can be 1-8.

So I'm wondering if using regular expressions to would be possible/practical and if so, could anyone let me know what they are? I'm thinking that I should just use a conditional statement with logical-ors for the piece type but I'm curious to know if there are other solutions.


Solution

  • Regular Expressions on the inputs:

    • Piece: ^[p|r|b|n|q|k|P|R|B|N|Q|K]$
    • Position: ^[A-H|a-h][1-8]$

    You could evaluate onblur, onchange, and onsubmit for the form.

    I do agree that validating the move on the Client-Side and Server-Side would make a lot of sense as well.